c++ - 我如何接受 double 输入并执行 IF ELSE 语句

标签 c++ if-statement double decimal

#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 (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";
    }
}

关于c++ - 我如何接受 double 输入并执行 IF ELSE 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58323428/

相关文章:

c++ - visual studio 链接器警告 LNK4098

c++ - 尺寸非常大的二维 vector

c++ - 如何访问 vector 迭代器中的类变量?

java - 如何让程序读取秒表,然后在时间到达那一秒时在另一个 TextView 框中打印语句

Java double /整数

java - 使用 DocumentFilter 仅接受 JTextField 中的 double 值

c++ - 捕获从其参数抛出的函数中的异常

java - If 语句与 String.equals()

c - AND 和 OR 运算符 c

ios - 从不兼容类型 'double*' 分配给 'double'