【问题标题】:How to end a loop in C?如何在C中结束循环?
【发布时间】:2018-11-26 07:28:14
【问题描述】:

如果为 temp 输入了 n,我正在尝试终止 for 循环并结束程序。 CaseCheck 函数返回 1 如果 temp = 'Y' 和 0 在所有其他情况下,此函数被测试正常工作。

现在,无论何时more = 0,程序都会尝试以相同的c值再次运行for循环,而如果more = 1,它将运行下一个c值。

    int main()
    {
        char grades[100];
        float v[100];
        float w[100];

        int more = 1;
        char temp;

        while (more = 1)
        {
            for (int c = 0; c < 100; c++)
            {   
                printf("\n\nThis is Assignment number %d\n\nPlease enter the available mark for this assignment\n", c+1);
                scanf("%f", &v[c]);
                printf("\nPlease enter the awarded mark for this assignment");
                scanf("%f", &w[c]);
                grades[c] = GradeFromRawMarks(v[c],w[c]);
                printf("Is there another assignment? Enter Y/N");
                scanf("%s", &temp);
                more = CaseCheck(temp,'Y');
            }
        }


        return 0;
    }

【问题讨论】:

  • more = 1 --> more == 1。并打开你的编译器警告。
  • 尝试调试。 more=1 是一个作业!
  • scanf("%s", &amp;temp); 获取了错误的类型(并传递了错误的值)。应该是scanf(" %c", &amp;temp);。注意%c之前的额外空格。
  • 请注意,将 more 设置为 0 不会超出您的 for 循环。
  • ... 因此,您可能会通过在 char 变量中输入 2 个字节(一个字母,一个字符串终止符)来破坏某些内容。

标签: c function for-loop


【解决方案1】:

如果 temp 为 'n',则可以返回

if (temp == 'n')
    return (0);

此外,您不应读取带有用于字符串的"%s" 格式说明符的char 类型。而是使用%c 阅读您的char。详情请见man scanf

【讨论】:

  • 我在 for 循环的末尾添加了if (more == 0); {break;},但现在无论more 是什么值,循环都会中断。
  • 删除 if 条件和大括号之间的 ';'
  • @LeoWang 您仍在尝试将字符串输入到单个字符中 - 正如评论所言,请注意编译器警告。
猜你喜欢
  • 2010-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-22
  • 1970-01-01
相关资源
最近更新 更多