Xiang Wang
Xiang Wang

Reputation: 69

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

Upvotes: 1

Views: 409

Answers (2)

Ashwani
Ashwani

Reputation: 2052

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.

Upvotes: 1

Pascal Cuoq
Pascal Cuoq

Reputation: 80335

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.

Upvotes: 6

Related Questions