You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言计算平均分程序首次输入-1终止时输出-nan问题求解

问题产生原因

当用户首次输入就输入-1时,while循环不会执行,计数器counter始终保持初始值0。后续执行average = total / counter时触发浮点数除以0运算,在C语言标准中,浮点数除0的结果为NaN(Not a Number,含义为非合法数值),你看到的-nan就是这类非法运算的输出。

修复方法

在计算平均值前增加判断逻辑:如果counter为0,说明没有输入有效分数,直接输出提示即可;仅当counter大于0时再计算并输出平均值。

修改后的完整代码如下:

#include <stdio.h>
int main()
{
     int counter = 0;
     float grade;
     float total = 0;
     float average;
     printf("Compute the average grades.\n");
     printf("Grade = -1 will terminate the process\n");
     printf( "Enter grade (-1 to terminate): " );
     scanf("%f",&grade);
     while(grade != -1)
     {
         counter++;
         total+=grade;
         printf( "Enter grade (-1 to terminate): " );
         scanf("%f",&grade);
     }
     // 新增有效输入判空逻辑
     if(counter == 0) {
         printf("未输入有效分数\n");
     } else {
         average = total / counter;
         printf("班级平均分为 %.2f\n", average);
     }
     return 0;
}

内容的提问来源于stack exchange,提问作者user14947646

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 09:27:05