【问题标题】:How can i accept input as an double and perform IF ELSE statement我如何接受输入作为双精度并执行 IF ELSE 语句
【发布时间】: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


【解决方案1】:

在我的平台上,将常量更改为 long double 常量修复了不当行为。

浮点数(floatdoublelong 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";
    }
}

【讨论】:

    猜你喜欢
    • 2020-08-03
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    • 1970-01-01
    相关资源
    最近更新 更多