为什么我的代码给了我错误的结果?
Why my code is given me wrong results?
我不知道为什么我的代码给了我不正确的结果。
当我输入像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
来表示a
和b
:
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
相关文章:
- 如何修复循环中的错误产生的错误结果?
- 添加可变参数函数的错误结果
- 使用特征 3 线性系统求解器的错误结果
- 按位包含 OR 的错误结果
- 如果我将索引变量更改为零,并且合并函数中的k = 0,则获得合并排序的错误结果
- STD :: FPCLASSIFY的错误结果使用Valgrind进行长时间的双重双重结果
- 视觉工作室的错误结果
- 将C#struct传递给C 不受管理的DLL返回错误结果
- 最长的常见子字错误结果
- 华氏度到摄氏度的错误结果
- UE4中简单坐标变换的错误结果
- 记忆错误结果的说明[编译器行为]
- 如何解决错误PRJ0002:错误结果 -1073741515从"cl.exe"返回?
- 错误 PRJ0002:错误结果 -1073741515 从"C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\cl.
- glGetUniformLocation OpenGL ES 2.0(在ipad 3 iOS 7.0.3上返回错误结果)
- 在模板函数中调用std::for_each时出现错误结果
- 使用copy和back_inserter将矢量附加到其自身时出现错误结果
- CUDA 线程在全局内存中的私有位置写入时出现错误结果
- 来自 c++ 代码的错误结果
- 使用浮点值和铸造的算术运算的错误结果 - 差异很大,我想这不是准确值的情况(429497)?