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

C++奇偶判断程序输入12位及以上大数值报错如何解决

问题产生原因

当前代码使用int类型存储输入的整数,主流编译环境下32位有符号int的取值范围仅为 -2147483648 ~ 2147483647,最多支持10位有效十进制整数。输入12位超大整数时会超出int的存储上限,触发整数溢出属于C++标准中的未定义行为,会导致输入读取失败、变量存储异常值,最终出现判断结果错误甚至程序运行崩溃的问题。

修复方案

可以根据实际需求选择以下两种修复方式:

  • 方案一:替换为更大范围的整数类型
    使用long long类型替代int,64位有符号long long的取值范围可达 -9223372036854775808 ~ 9223372036854775807,最大支持19位十进制整数,完全覆盖12位整数的使用需求。
    修复后代码如下:
#include<iostream>
using namespace std;

int main(){
    cout<<"This program is for finding if the provided integer is even or odd.\nPls provide the integer...\n";
    long long a;
    cin>>a;
    if(a%2==0){
        cout<<"The provided integer is even.";
    }
    else{
        cout<<"The provided integer is odd.";
    }
    return 0;
}
  • 方案二:字符串处理适配任意长度整数
    如果后续需要支持超过19位的超大整数,无需转数值存储,直接将输入作为字符串读取,判断最后一位字符的奇偶性即可,没有长度限制:
#include<iostream>
#include<string>
using namespace std;

int main(){
    cout<<"This program is for finding if the provided integer is even or odd.\nPls provide the integer...\n";
    string s;
    cin>>s;
    // 取最后一位字符转数字判断奇偶
    int last = s.back() - '0';
    if(last % 2 == 0){
        cout<<"The provided integer is even.";
    }
    else{
        cout<<"The provided integer is odd.";
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 13:15:03