我是 C 編程的新手,我正在嘗試制作一個程式,列印系列的第 n 個術語,每 5 個計數,它加起來 5。
示例:1、2、3、4、9、10、11、12、17、18、19、20、25 ...... _ _ _
這是我的代碼
int num,digit,count = 1;
printf("Enter n: ");
scanf("%d", &num);
for(int i=1; i<=num; i ){
count ;
if(count > 5){
count = 0;
i =4;
}
printf("%d ",i);
}
我的代碼沒有達到我要求的特定第 n 個術語。例如,我輸入了 10,它只顯示到第 6 個學期
uj5u.com熱心網友回復:
要做的事情是弄清楚你想做什么以及你將如何去做。與其修補代碼,不如將事情分解成簡單的部分并使其清晰。
#include <stdio.h>
int main(void)
{
int num = 10;
// Method 1: Spell everything out.
// i counts number of terms printed.
// j counts number of terms since last multiple of four terms.
// k is current term.
for (
int i = 0, j = 0, k = 1; // Initialize all counters.
i < num; // Continue until num terms are printed.
i) // Update count.
{
printf("%d ", k); // Print current term.
j; // Increment four-beat count.
if (4 <= j)
{
// Every fourth term, reset j and increment the term by 5.
j = 0;
k = 5;
}
else
// Otherwise, increment the term by 1.
k = 1;
}
printf("\n");
// Method 2: Use one counter and calculate term.
// Iterate i to print num terms.
for (int i = 0; i < num; i)
/* Break the loop count into two parts: the number of groups of 4
(i/4) and a subcount within each group (i%4). Looking at the
starts of each group (1, 9, 17, 25...), we see each is eight
greater than the previous one. So we multiply the group number by
8 to get the right offsets for them. Within each group, the term
increments by 1, so we use i%4 directly (effectively multiplied by
1). Then (i/4)*8 i%4 would start us at 0 for i=0, but we want to
start at 1, so we add 1.
*/
printf("%d ", (i/4)*8 i%4 1);
printf("\n");
}
uj5u.com熱心網友回復:
用這個替換你的回圈,它也可以作業:
for(int i=0, j=1, count=1; i<num; i , j , count )
{
printf("%d ", j);
if(count == 4)
count = 0, j =4;
}
uj5u.com熱心網友回復:
您不得更改 for 回圈體內的變數 i。
您需要再引入一個變數來存盤當前輸出的數字。
這是一個演示程式。
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter n: " );
scanf( "%u", &n );
for ( unsigned int i = 0, value = 0, count = 1; i < n; i )
{
if ( count == 5 )
{
value = 5;
count = 1;
}
else
{
value;
}
printf( "%u ", value );
count;
}
}
程式輸出為
Enter n: 13
1 2 3 4 9 10 11 12 17 18 19 20 25
uj5u.com熱心網友回復:
這是另一種我認為不太復雜的觀點,在評論中有解釋:
#include <stdio.h>
int main(void)
{
int num, count = 1;
num = 20;
// if you look closely, you actually have an initial condition before the
// main pattern starts. Once the pattern starts, its actually every _fourth_
// term that gets added by 5. You'll make things easier on yourself if you
// print out this initial condition, then handle the pattern in the loop.
// If you really want to be correct, you can wrap this in a if (num > 0) check
printf("%d ", count );
// start at 1, because we already printed the first item
for(int i=1; i<num; i , count )
{
// now we can focus on every fourth term
if (i % 4 == 0)
{
// if it's the fourth one, add 5 to the previous value
// Of course this simplifies to count = 4
count = (count-1) 5;
}
printf("%d ",count);
}
}
示范
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/427726.html
