【发布时间】:2019-10-11 00:26:10
【问题描述】:
#include <iostream>
#include <sstream>
using namespace std;
using std::stringstream;
using std::cout;
int main()
{
double value;
cout << "Enter a number : " << endl;
cin >> value;
cout << "The exact number : ";
cout << value << endl;
system("pause");
}
写完这段代码后,我发现在 IF ELSE 语句中每个变量的双精度值都会四舍五入,我如何才能将输入的确切值输入到 IF ELSE 语句中?例如:输入为 0.007447,如果输入小于等于 0.007447 会提示另一个输入。但在这种情况下,用户输入为 0.007447 后,将四舍五入为 0.00745,因此它会运行 else 语句而不是 if 语句。
【问题讨论】:
-
sampleV是一个长双精度数。0.007447是双重的。如果使用 long double 常量会有什么不同吗? -
您真的需要 all 代码来演示您的问题吗?请阅读minimal reproducible example。
-
使用浮点数时不要混合精度。将 0.007447 读入
long double并不能得到与转换0.007447文字(表示double)相同的近似值。也不完全是 0.007447,因为它不能用二进制浮点数精确表示。 -
由于双精度/浮点不精确,必须通过检查双精度是否真的彼此接近来检查双精度是否相等。由于“非常接近”不是一个确切的定义,因此存在几种方法,请参阅stackoverflow.com/questions/17333/…
标签: c++ if-statement double decimal