这个输入中float和double有什么区别?

Xia*_*ang 1 c++ floating-point double

我有两个输入,唯一的区别是我在第二个输入中用"float"替换"double".但是,第一个可以按预期运行,但不能运行第二个.第二个不以0.1的输入结束.有谁对此有一些想法?非常感谢!

第一输入:

#include <iostream>

using namespace std;

int main()
{
    double input;
    input = 0;
    double sum = 0;
    cout << "Please enter a series numbers and end with 0.1: ";
    cin >> input;
    while (input != 0.1)
    {
        sum += input;
        cout << "The cumulative sum is: " << sum << endl;
        cin >> input;
    }
    return 0;
}


Please enter a series numbers and end with 0.1: 1 2 3 0.1
The cumulative sum is: 1
The cumulative sum is: 3
The cumulative sum is: 6
Run Code Online (Sandbox Code Playgroud)

第二输入:

#include <iostream>
using namespace std;

int main()
{
    float input;
    input = 0;
    float sum = 0;
    cout << "Please enter a series numbers and end with 0.1: ";
    cin >> input;
    while (input != 0.1)
    {
        sum += input;
        cout << "The cumulative sum is: " << sum << endl;
        cin >> input;
    }
    return 0;
}


Please enter a series numbers and end with 0.1: 1 2 3 0.1
The cumulative sum is: 1
The cumulative sum is: 3
The cumulative sum is: 6
The cumulative sum is: 6.1
Run Code Online (Sandbox Code Playgroud)

Pas*_*uoq 6

0.1在条件(input != 0.1)double最接近理性1/10.在float最接近这种理性的,0.1f代表不同的值,并且不使这一情况属实.

如果要float在程序中使用,请使用(input != 0.1f)相应的条件.

  • 一般来说,你永远都不应该将浮点数与平等进行比较.请参见http://stackoverflow.com/questions/588004/is-floating-point-math-broken (6认同)
  • @ o11c公平地说,我在C中完成了大部分编程,最后两个标准比C++关于允许过高精度的条件更加强调.我有时认为C++ 11,其中描述`cfloat`的句子"内容与标准C库头<float.h>相同",应该具有相同的规则,因为这个头定义了`FLT_EVAL_METHOD`,但是例如,这是GCC作者不相信的一个微弱的论点(因为他们没有让选项`-fexcess-precision = standard`适用于C++前端). (2认同)