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

检查回文数的C程序运行异常:无限循环及浮点异常求助

回文数检测程序的死循环与浮点异常问题分析

问题描述

编写的C程序用于检查数字是否为回文数,编译正常,但输入数据后程序始终无法停止运行,强制终止时提示“floating point exception (core dumped)”。测试用代码如下:

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

int NumOfDigits(long long x) {
    int sum = 1;
    while (x / 10 != 0) {
        sum ++;
        x = x / 10;
    }
    return sum;
}

int isPal(long long x) {
    int f, c, front, back, sum;
    sum = NumOfDigits(x);
    
    c = pow(10,(sum-2));
    front = x / pow(10,(sum - 1));
    back = x % 10;
    f = 1; 

    while (x != 0 && f == 1) {
        if (front == back) {
           x = (x / 10) % c;
           c /= 100;
           sum -=2;
           front = x / pow(10,sum);
           back = x / 10;
        } else {
           f = 0;
        }
    }
    if (f) {
        return 1;
    } else {
        return 0;
    }
}

int main() {
    int f;
    long long x;
    scanf("%lld\n", &x);
    f = isPal(x);
    if (f) {
        printf("yes"); }
        else { printf("no"); }
}

问题原因分析

  • scanf格式字符串错误:scanf("%lld\n", &x); 中的\n会让scanf持续等待输入,直到遇到非空白字符,导致输入后程序无法继续执行,表现为“无法停止运行”。
  • 整数运算误用浮点函数pow:pow是浮点运算函数,返回double类型,用它参与整数除法或赋值给int变量会产生精度误差(例如pow(10,3)可能返回999.999999999,赋值给int后变为999)。当循环中sum减为负数时,pow(10, sum)返回小于1的小数,导致c最终变为0,触发x % c的整数除零操作,这就是“floating point exception (core dumped)”的直接原因。
  • back变量赋值错误:代码中back = x / 10; 应为back = x % 10;,当前写法取的是去掉最后一位的数值而非最后一位数字,导致回文判断逻辑完全错误,循环无法正常终止。
  • 循环逻辑漏洞:当sum减到1或0时,pow(10, sum)的计算会出现异常,且此时x可能已经变为0,但错误的判断逻辑会让循环继续执行,加剧死循环问题。

关键修正点示例

  1. 修正scanf格式:
scanf("%lld", &x);
  1. 替换pow为自定义整数幂函数,避免浮点误差:
int power10(int n) {
    int res = 1;
    for (int i = 0; i < n; i++) {
        res *= 10;
    }
    return res;
}

在isPal函数中使用power10(sum-2)替代pow(10, sum-2),以此类推。
3. 修正back变量赋值:

back = x % 10;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 11:01:26