gpt4 book ai didi

有人可以帮助修复我的 while 循环吗?它永远运行

转载 作者:行者123 更新时间:2023-11-30 21:20:19 25 4
gpt4 key购买 nike

我正在尝试运行下面的代码,但我进入了一个无法退出的循环。

错误消息应该出现,然后用户应该能够输入正确的范围值。

有人可以修复这个无限循环,以便它仅在用户输入超出范围的值时出现。

#include<stdio.h>

int main(void) {

int students, counter, total;
int marks[40];
int stdno[40];
total = 0;

printf(" ---=== IPC mark Analyser V2.0 ===---\n");
printf("Please enter the number of students(between 3 and 40):");
scanf("%d", &students);

while (students < 3 || students >40) {
printf("Invalid number, enter a number between 3 and 40 inclusive:");
scanf("%d", &students);
}

printf("Row Std No Mrk\n");
printf("--- --------- ---\n");

for (counter = 0; counter < students; counter++) {
printf(" _________ ___\r");
printf("%03d ", counter + 1);
scanf("%09d %3d", &stdno[counter], &marks[counter]);

while (marks < 0 || marks >100 || stdno < 10000000 || stdno > 999999999) {
printf("Error: Enter values between 0 and 100 inclusive.\n");
scanf("%09d %3d", &stdno[counter], &marks[counter]);
}

return 0;
}
}

最佳答案

  1. 首先是您拥有的 wile 循环条件 while (marks < 0 || marks >100 || stdno < 10000000 || stdno > 999999999)是不正确的。 marksstdno是数组,不能与数字进行比较。您甚至会收到编译器警告。您需要做的是与数组元素 marks[counter] 进行比较和stdno[counter] 。这样,您在循环中输入的每个值都会根据条件进行检查。

  2. while 循环应运行两个语句: printfscanf 。在您当前的代码中,while 循环将仅执行 printf每次。你需要戴上牙套{围绕这两个陈述。

    while (marks[counter] < 0 || marks[counter] >100 || stdno[counter] < 100000000 || stdno[counter] > 999999999)
    {
    printf("Error: Enter values between 0 and 100 inclusive.\n");
    scanf("%09d %3d", &stdno[counter], &marks[counter]);
    }

您可以通过打印上面相同的数字来向用户提供指示来进一步改进这一点。

while (marks[counter] < 0 || marks[counter] >100 || stdno[counter] < 100000000 || stdno[counter] > 999999999)
{
printf("Error: Enter values between 0 and 100 inclusive.\n");
printf(" _________ __\r");
printf("%03d ", counter + 1);
scanf("%09d %3d", &stdno[counter], &marks[counter]);
}

关于有人可以帮助修复我的 while 循环吗?它永远运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39952468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com