#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语句中,每个变量的double都会四舍五入,如何才能将输入的精确值取到IF ELSE语句中呢?例如:输入为0.007447,如果输入小于或等于0.007447,将提示再次输入。但在这种情况下,用户输入 0.007447 后,它会四舍五入为 0.00745,因此它会运行 else 语句而不是 if 语句。
最佳答案
在我的平台上,将常量更改为 long double
常量修复了错误行为。
float (float
、double
、long double
)在数学上不是实数。而不是精度有限。
更多详情请访问 What Every Computer Scientist Should Know About Floating-Point Arithmetic .
此外,您的示例比您需要的要大得多。一个最小的例子可以很容易地表达成这样(包括“修复”):
#include <iostream>
#include <sstream>
using std::stringstream;
using std::cout;
int main() {
long double value;
stringstream ss("0.007447");
ss >> value;
if (value <= 0.007447) {
cout << "value <= 0.007447 ==> TRUE -- as expected\n";
} else {
cout << "value <= 0.007447 ==> FALSE -- unexpected!\n";
}
if (value <= 0.007447L) {
cout << "value <= 0.007447L ==> TRUE -- as expected\n";
} else {
cout << "value <= 0.007447L ==> FALSE -- unexpected!\n";
}
}
关于c++ - 我如何接受 double 输入并执行 IF ELSE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58323428/