我正在做一些作业,我的任务是用C编写一个程序,该程序使用一个从1到10计数的循环,并使用该循环的计数器来计算最多5的倍数。我创建了一个计数循环,可以正确计数到10,但是我目前停留在的位置是任务的第二部分。我试图创建一个新的循环,但是它没有按照我想要的方式工作。
#include <stdio.h>
int main (void) {
int counter = 1;
// heading
puts("Number\t 1st\t 2nd\t 3rd\t 4th\t 5th");
// loop that counts to 10
while (counter <= 10) {
printf("%d\n", counter);
counter++; // adds +1 to the counter
}
// stuck on this part
// loop that attempts to take the 10 numbers from prior loop and display their multiples up to 5 times
while (counter <=10) {
printf("%d", counter);
counter = counter * 1;
counter = counter * 2;
counter = counter * 3;
counter = counter * 4;
counter = counter * 5;
}
}
这就是我想要的样子:
您不想这样做:
printf("%d", counter);
counter = counter * 1;
counter = counter * 2;
counter = counter * 3;
counter = counter * 4;
counter = counter * 5;
您将计数器乘以1*2*3*4*5 = 120
每次迭代!相反,您想让计数器继续运行1, 2, 3, ...
并直接打印倍数:
int counter = 1;
while (counter <= 10) {
printf("%d\t %d\t %d\t %d\t %d\t %d\n",
counter * 1,
counter * 1,
counter * 2,
counter * 3,
counter * 4,
counter * 5);
counter++;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句