基本上是标题,我在初学者C++班,正在尝试做作业,但由于covid,在没有动手教学的情况下一直难以学习。我正在尝试使用 while 循环对数字求和和平均,但在输入字符或字符串而不是双精度时让它停止。我认为除了条件之外,我的所有代码都可以工作,任何帮助将不胜感激。
#include <stdio.h>
int main(int argc, const char* argv[])
{
double userNum, numSum, numAvg;
int i; //iterations for calculating average
userNum = 0.0;
numSum = 0.0;
numAvg = 0.0;
i = 0;
while (1)
{
if (1) {
printf("Enter a score (or stop to quit):n");
scanf("%lf", &userNum);
}
else // I thought this would break the loop if any nun double value was entered but I was wrong?
{
break;
}
numSum = numSum + userNum;
i++;
}
if (i == 0) // if no ittereations done, gives no sum message
{
printf("No sum and average calculated!");
}
else
{
// otherwise calculates and prints sum and avg
}
{
numAvg = numSum / i;
printf("The sum is: %0.2lf, average is: %0.2lf", numSum, numAvg);
}
return 0;
}
if(1)
是多余的,通过添加它,你永远不会达到else
。
它等同于if (1 != 0)
总是正确的。
您可以通过检查scanf()
的返回值来实现您要求的内容。您可以像这样修改代码:
while (1)
{
printf("Enter a score (or stop to quit):n");
if (scanf("%lf", &userNum) != 1) // should return 1 if 1 double is read
{
break;
}
numSum = numSum + userNum;
i++;
}
对于大型输入,我建议您切换到fgets()
,然后使用sscanf()
解析字符串。scanf()
不提供任何针对算术溢出的保护,算术溢出是未定义的行为。