【问题标题】:How can I use a counting loop to calculate multiples of a number?如何使用计数循环来计算数字的倍数?
【发布时间】:2021-05-20 18:01:56
【问题描述】:

我正在做一些作业,我的任务是用 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;
    }
}

这就是我想要的样子:

【问题讨论】:

    标签: c loops counter multiplication


    【解决方案1】:

    你不想这样做:

        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++;
    }
    

    【讨论】:

    • 哦,好吧,我跟着你。而不是创建另一个循环,我只需要打印与我放在标题中相同数量的数字,以便它们同时计数和相乘。谢谢!
    【解决方案2】:

    更多信息,如果你想把一个循环放在另一个循环中,你可以这样做:

    #include <stdio.h>
    
    int main (void)
    {
       printf("Number\t1st\t2nd\t3rd\t4th\t5th\n");
       for (int rows = 1; rows <= 10; rows++) {
         printf("%d", rows);
         for(int cols = 1; cols <= 5; cols++) {
             printf("\t%d", rows * cols);
         }
         printf("\n");
       }
       return 0;
    
    } // main
    

    但出于您的目的,选择的答案更好!

    【讨论】:

    • for 循环不会更好
    • @EdHeal 我不确定。我们还没有涵盖for 循环。
    • @HungryMoose for 循环简化了后续 int = 0;而(i
    • @dreamcrash 我喜欢两个人​​!谢谢!
    猜你喜欢
    • 2011-09-29
    • 1970-01-01
    • 2021-09-09
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多