gpt4 book ai didi

c - 为我的程序提供一点帮助 : infinite loop in the scanf

转载 作者:行者123 更新时间:2023-11-30 20:40:44 26 4
gpt4 key购买 nike

我的程序获得 5 个等级并计算平均值和最大值。但是当我先输入字母而不是等级时,它会连续打印“无效”。当我在输入 int 值后输入一个字母时,它会停止进一步获取剩余值。有人可以解释我错在哪里吗?谢谢

#include <stdio.h>
#include <stdlib.h>


int main()
{
int grade[5];
int temp;
int temp2 = 0;
for(int i = 0; i <= 4; i++) //getting inputs
{
printf("enter grade= ");
scanf("%i", &temp);
if(temp <= 100 && temp >= 0)
grade[i] = temp;
else
{
printf("invalid\n");
i--;
}
}

//print array
for(int i = 0; i <= 4; i++)
printf("%i\n", grade[i]);

//Average
for(int i = 0; i <= 4; i++)
{
temp2 = temp2 + grade[i];
}

printf("avg is= %i\n", temp2 / 5);

//Max
int mx = grade[0];

for(int i = 1; i <= 4; i++)
if(mx < grade[i])
{
mx = grade[i];
}
printf("max is= %i", mx);

return 0;
}

最佳答案

来自 scanf 手册页:

These functions return the number of input items successfully
matched and assigned, which can be fewer than provided for, or
even zero in the event of an early matching failure.

因此,当扫描失败时,您必须读取并抛出有问题的字符,否则它仍然会在缓冲区中。

关于c - 为我的程序提供一点帮助 : infinite loop in the scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20879377/

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