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

C语言简易计算器输入大数返回NaN问题求助

输入大数时C语言计算器出现inf/NaN的原因及解决办法

问题根源

你的计算器使用float类型存储数值,而单精度浮点数(float)的取值范围有限:标准float能表示的最大值约为3.4×10^38,当输入的数值超过这个上限时,变量会溢出并被标记为inf(无穷大)。如果后续用inf参与运算(比如inf / inf),结果就会变成NaN(非数值),这就是你遇到的问题。

解决办法

1. 改用双精度浮点数(double)

double是双精度浮点数,取值范围远大于float(约1.7×10^308),能轻松处理更大的数值,同时精度也更高,更适合计算器这类需要数值准确性的场景。

2. 匹配格式符

使用double后,输入时要把scanf里的%f改成%lf;输出时printf可以用%f或%lf(C语言中printf会自动提升float为double,所以两者都可行,但统一用%lf更规范)。

3. 增加输入有效性验证

检查scanf的返回值,确保用户输入的是合法数字,避免非法输入导致的未定义行为。

4. 优化运算符判断逻辑

用switch语句替换多个if-else,代码更简洁易读。

修改后的完整代码

/*
Declare and initialize variables and/or constants using appropriate data types -- X

Read in input from the user and output data & information to the user in a meaningful manner -- X

Use the mathematical operators – addition, subtraction, multiplication, division, and modulus (remainder) 
– in expressions and calculations -- X

Use decision making structures such as if, if/else, and switch to affect program flow -- X

Use control structures such a while, do-while, and for loops to implement repetition in code -- X
*/
#include <stdio.h>
#include <stdbool.h>

// 改用double类型存储数值
double num1 = 0; 
double num2 = 0;
double finalResult = 0;
char operator = '+';
bool opReal = false;

int main() {
    // 输入第一个数并验证有效性
    printf("Enter a number: ");
    while (scanf("%lf", &num1) != 1) {
        // 清空输入缓冲区的非法内容
        while (getchar() != '\n');
        printf("Invalid input, please enter a number: ");
    }
    printf("\n");
    
    // 输入第二个数并验证有效性
    printf("Enter another number: ");
    while (scanf("%lf", &num2) != 1) {
        while (getchar() != '\n');
        printf("Invalid input, please enter a number: ");
    }
    printf("\n");
    
    // 输入运算符并验证
    do {
        printf("Enter either + - * or /: ");
        scanf(" %c", &operator);
        // 用switch简化判断逻辑
        switch(operator) {
            case '+':
            case '-':
            case '*':
            case '/':
                opReal = true;
                break;
            default:
                opReal = false;
                printf("Invalid operator, please try again.\n");
                break;
        }
    } while (!opReal);
    
    printf("num1: %lf\n", num1);
    printf("num2: %lf\n", num2);
    printf("operator: %c\n", operator);
    
    // 执行计算
    switch(operator) {
        case '-':
            finalResult = num1 - num2;
            break;
        case '+':
            finalResult = num1 + num2;
            break;
        case '*':
            finalResult = num1 * num2;
            break;
        case '/':
            // 额外处理除数为0的情况
            if (num2 == 0) {
                printf("Error: Division by zero is not allowed.\n");
                return 1;
            }
            finalResult = num1 / num2;
            break;
    } 
    printf("Final Result: %lf\n", finalResult);
    
    return 0;
}

关键修改说明

  • 将所有浮点变量从float改为double,提升数值范围和精度。
  • 给输入步骤增加了有效性验证,处理非法输入的情况。
  • 用switch替换冗余的if-else,代码结构更清晰。
  • 增加了除数为0的判断,避免出现除以0导致的inf或NaN。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:45:37