如何在不知道循环何时停止的情况下创建循环?

时间:2015-10-29 00:43:50

标签: c

我正在尝试创建一个带有数字的程序,我们将该数字与存储了特定数字的变量相匹配。我们需要继续这样做,直到用户输入与我们在变量中存储的数字相匹配的正确数字:

#include <stdio.h>
int main(void) {

        int i;
        int j;
        int num1;
        int num2 = 2;

        printf("Enter number");
        scanf("%d", &num1);

        while (num1 == 0) {

                printf("Enter number");
                scanf("%d", &num1);
        }

        while (num1 != num2) {

                for(j=1;j
                printf("This is not the correct number! \n");
                printf("Enter number again: ");
                scanf("%d", &num1);
        }

        if (num1 == num2) {

                printf("The numbers have matched! \n");
        }
}

我对如何创建循环感到困惑,我们不知道用户输入错误号码的次数。我想要的循环是显示 是用户输入错误号码的次数。如果他们进入3次就说了。

    This is not the correct number 1!
    This is not the correct number 2!
    This is not the correct number 3!

但我们不知道用户输入错误号码的次数,所以我在循环中放入了什么条件,因此它很重要。

1 个答案:

答案 0 :(得分:2)

您想要创建一个单独的计数器变量来跟踪您完成循环的次数。在循环之前将其设置为0,然后在每次迭代时递增。

EmbeddedFileProvider

另外,我认为这是一个错字:

   int count = 0;
   ...
   while (num1 != num2) {
            count++;
            printf("This is not the correct number %d! \n", count);
            printf("Enter number again: ");
            scanf("%d", &num1);
    }