Program doesn't work as expected

closed account (oSzvC542)
My task is to create a program which inputs a positive real number and returns the hundredths digit of that number. For example, entering 34.55 should return 5. Here's my program.
1
2
3
4
5
6
7
8
9
10
#include<iostream>
using namespace std;
int main()
{
    double x;
    cin>>x;
    int y=x*100;
    cout<<y%10;
    return 0;
}

If I enter 12.123, it returns 2. So everything's OK. Problem is entering 34.55 returns 4. For testing purposes, I changed cout<<y%10; to cout<<y; and it turned out y equaled 3454 when I input 34.55. I don't understand. 34.55x100 = 3455 and clearly y should be 3455. Could that be a problem with my compiler. I'm using Codeblocks.
I think the problem is just floating point values being iffy. Don't take my word on it though.
I think it's the inherent properties of floating-point values which are stored internally in binary. Thus an exact decimal value may be stored internally as an approximation.

This is much the same as the way we put 0.33333333 as an approximation for 1/3. Some values can be expressed precisely in decimal notation, and others cannot; the same applies to binary.

Try this:
1
2
3
    double x = 34.55;
    int y =  x*10000 ;
    cout << y ;


My compiler gives me
345499


A suggestion is to add 0.5 to the result of the calculation before converting to an integer, like this. Without this, the conversion to int simply truncates the value with no rounding.

 
    int y =  x*100 + .5 ;


Last edited on
Topic archived. No new replies allowed.