为什么我的代码给我错误的结果?

时间:2018-04-12 01:38:33

标签: c++

我不知道为什么我的代码会给我错误的结果。

当我输入6670680902之类的数字时,结果为6.67068e+0.766706800)。这不是正确的结果。 当我使用计算器时,667006080902 / 100的正确结果为66706809.02

我该怎么办才能修复它?

#include "stdafx.h"
#include "conio.h"
#include "iostream"

using namespace System;
using namespace std;

int main()
{
    float a;
    float b;

    cout << "Ingrese el codigo: "; cin >> a;

    b = a / 100;

    cout << "result: " << b;

    _getch(); 
    return 0;
 }

2 个答案:

答案 0 :(得分:3)

这里的第一个问题是默认情况下C ++会使用科学记数法显示更大的数字,there are ways to prevent this for floating point numbers就像浮点数一样。一种简单的方法是在您的号码前添加<< fixed

cout << "result: " << fixed << b;

将返回66706812.0

下一个问题是floats不擅长精确,这就是数字仍然不正确的原因。 Floats are less precise compared to something like a double which has twice the precision。如果您使用double代替ab

int main()
{
    double a;
    double b;
    //...
    cout << "result: " << fixed << b;
    //...
}

您将获得所期望的价值:66706809.02

答案 1 :(得分:1)

可以使用'limits`

#include "iostream"
#include <string>
#include <limits>

using namespace System;
using namespace std;

int main()
{
 double a;
 double b;

 cout << "Ingrese el codigo: "; cin >> a;

 b = a / 100;

  cout.precision(numeric_limits<double>::digits10 + 1);

  cout << "result: " << b << endl;
  _getch(); 
 return 0;
 }

输出:

result: 66706809.02
相关问题