C for loop故障排除

时间:2017-10-06 15:51:09

标签: c

所以基本上我创建了一个程序来询问用户他们想要测试程序的次数。但我无法弄清楚我的for循环问题。所以:

  1. 如果用户想要测试该程序3次,则应该只询问3次的值,之后应该退出。
  2. 这是我的代码如下:

    #include <stdio.h>
    
    int main()
    {
    
    
        int test;
        printf("How many times do you want to test the program?");
        scanf("%d", &test);
        test = 0; // Reinitializing the test from 0
        for (test=0; test=>1; test++) //I cant figure out whats going on with the for loop.
        {
            printf("Enter the value of a: \n");
            scanf("%d", &test);
            ;
    
        }
        return 0;
    }
    

    输出应为: “你想要多少次测试程序”:3 输入a的值:任何数值 输入a的值:任何数值 输入a的值:任何数值 (出口)

1 个答案:

答案 0 :(得分:1)

在代码的这一部分:

scanf("%d", &test);
test = 0; // Reinitializing the test from 0
for (test=0; test=>1; test++) 

首先,test拥有的内存中填充了用户输入的值。 (这没关系)
接下来,通过将test设置为零来使内存中的新值无效。 (这不行)
最后你的循环语句的构造是不正确的。

for循环的正确版本中,test应该是一个值,用作对其进行测试的限制,因为该索引在一系列值中递增,例如, 0到某个正值。

您可能打算:

scanf("%d", &test);
//test = 0; // Reinitializing the test from 0 (leave this out)
for(int i = 0; i <= test; i++)
{
    ...  

如果单独的索引值(i)递增并针对限制test进行测试。