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

Why my code is given me wrong results?

本文关键字:错误 结果 我的 代码 为什么      更新时间:2023-10-16

我不知道为什么我的代码给了我不正确的结果。

当我输入像6670680902这样的数字时,结果是6.67068e+0.7(这是66706800)。这不是正确的结果。 当我使用计算器时,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;
}

这里的第一个问题是默认情况下C++将使用科学记数法显示更大的数字,对于浮点数(如浮点数)有一些方法可以防止这种情况。一种简单的方法是在号码前添加<< fixed

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

这将返回66706812.0.

下一个问题是floats不擅长精确,这就是为什么数字仍然不正确的原因。与精度是双精度两倍的东西相比,浮点数的精度较低。如果您改用double来表示ab

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

您将获得期望的值:66706809.02

可以使用"限制"来完成

#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