【问题标题】:C++ wrong output in Windows SystemWindows系统中的C++错误输出
【发布时间】:2021-09-16 06:15:10
【问题描述】:

[在此处输入图像描述][1]我正在做一个非常简单的程序,将一些值转换为任何特定的数据类型,其中浮点数转换为 3 精度值和双精度值。这是我的代码:-

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
    int a;
    long b;
    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("%ld\n", b);
    printf("%c\n", c);
    printf("%.3f\n", d);
    printf("%.9lf\n", e);


    return 0;
}

测试用例:-

输入:- 3 12345678912345 a 334.23 14049.30493

正确的输出:-

3
12345678912345
a
334.230
14049.304930000

此代码通过了所有测试用例,但在 windows 中输出错误,我在 vscode、cmd、powershell 中尝试过。并且在在线编译器和 linux 系统中运行良好。

Windows 输出:- https://i.imgur.com/GrQJTyb.png

Linux 输出:- https://i.imgur.com/a5t4Hxu.png

如何在我的系统中解决这个问题,请帮忙。

【问题讨论】:

  • 请直接在此处发布输出,请勿使用外部链接。
  • 12345678912345 -- 这适合long吗? std::numeric_limits&lt;long&gt;::max() 是什么?此外,您没有提及您正在使用的实际 Windows 编译器。 VSCode 和 Powershell 不是 C++ 编译器。使用uint64_t,而不是long

标签: c++ windows gcc


【解决方案1】:

假设,Windows 类型“long”是 32 位大小。并且值“12345678912345”超过了这个大小。

【讨论】:

    【解决方案2】:

    规则是总是控制输入操作,而你不控制。

    这里有一个细微的变化,至少可以让我们了解正在发生的事情(使用 32 位模式):

    cin >> a;
    if (!cin) {
        perror("Read error on a");
        return 1;
    }
    cin >> b;
    if (!cin) {
        perror("Read error on b");
        return 1;
    }
    cin >> c;
    if (!cin) {
        perror("Read error on c");
        return 1;
    }
    cin >> d;
    if (!cin) {
        perror("Read error on d");
        return 1;
    }
    cin >> e;
    if (!cin) {
        perror("Read error on e");
        return 1;
    }
    

    它给出:

    Read error on b: Result too large
    

    在读取错误后,输入通道将拒绝读取任何其他内容,直到其状态被清除,因此bcde 将保留未初始化的值,因此您的随机结果.

    解决方法:像在 Linux 上一样使用 64 位模式,或明确使用 int64_t 64 位整数。

    修复:测试输入值是否可接受

    【讨论】:

    • 另一种解决方法是对 32 位和 64 位程序都使用 int64_t 而不是 long
    • @PaulMcKenzie:当然这是一种可能的解决方法!我已经用你的评论编辑了我的帖子。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2015-11-29
    • 2018-01-21
    • 2019-06-30
    • 2015-01-07
    • 1970-01-01
    相关资源
    最近更新 更多