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

C++精度转换代码Linux运行正常 Windows系统输出错误如何修复

问题根因

该异常由跨平台数据类型长度差异导致:

  • 64位Linux系统中long类型占8字节,可容纳的最大值约为9×10¹⁸,测试用例中的整数值12345678912345远小于该上限,无溢出问题
  • Windows系统中无论32位还是64位环境,long类型默认仅占4字节,可容纳的最大值为2147483647,测试用例的整数值远超过该上限,发生整数溢出,进而导致后续所有输入参数读取错位,输出全部异常。

修复方案

将代码中可变长度的long类型替换为跨平台统一为8字节的long long类型,同时同步修改printf对应的格式化标识符即可:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int a;
    long long b; // 替换long为long long
    char c;
    float d;
    double e;
    cin >> a >> b >> c >> d >> e;

    cout << "\nUsing cin & cout\n" << endl;
    cout << a << endl << b << endl << c << endl;
    cout << fixed << setprecision(3) << d << endl;
    cout << fixed << setprecision(9) << e << endl;

    cout << "\nUsing scanf and printf\n" << endl;
    printf("%d\n", a);
    printf("%lld\n", b); // 替换%ld为%lld适配long long
    printf("%c\n", c);
    printf("%.3f\n", d);
    printf("%.9lf\n", e);

    return 0;
}

注:原代码引入的<bits/stdc++.h>是非标准头文件,替换为标准输入输出精度控制需要的<iomanip>兼容性更好。

修改后代码可在Windows、Linux全平台正常运行,输出结果和要求完全一致。

内容的提问来源于stack exchange,提问作者code_Z.o

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 04:21:03