简体   繁体   中英

What is the difference between float and double in this input?

I have two input and the only difference is that I replace the "double" with "float" in the second input. However, the first one can run as expected but not the second one.The second one does not end with the input of 0.1. Any one have some ideas on this? Thanks very much!

First input:

#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

Second input:

#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

0.1 in the condition (input != 0.1) is the double closest to the rational 1/10. The float closest to this rational, 0.1f , represents a different value and does not make this condition true.

If you want to use float in your program, use (input != 0.1f) as the corresponding condition.

You have to explicitly cast 0.1 to float like:

while(input != (float)0.1)  

It is better to use explicit conversions while comparing floating point numbers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM