Wierd round on a float

I was practicing/learning C++ while came up with a problem that requierd me to derange large nunbers to units one at a time.
Like 157 get 1 then get 5 and then get 7 separatly.
While preforming this I noticed that multiply by 10 was rounding low my nunbers.
This got me 3 hours back and forth coding difrently and googling with no results.
Here it goes a demonstration of my problem.
I'm using wxDev-C++ with default settings.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>

main()
{
  float x,count=0;	
	
  scanf("%f",&x);   //Im talking about something larger than 100//
  
  while(x>10){
    x=x/10;         //getting base
    count++;
  }
  
  while(count>=0){
    x=x-(int)x;             //clearing unit
    x=x*10;                 //source of problem (I think) 
    printf("\nX=%f\n",x);   //geting output
    count--;               
  }
  
  fflush(stdin);  
  getchar();     
    
};


The output of this stuff to 157 is:


X=5.699999 //the problem starts right here
//instead of 5.700000 is that...
X=6.999993 //which keeps going enlarging the mistake

X=9.999933

I dont know how comon this is nor how to solve it.
I've been for something like 3 hours around this, can't find solution on google, or compiler settings, kind of going insane now.
Thnaks in advance =)

ps:Can this be a local problem? Caused by the compiler or machine?
Last edited on
I think it has to do with how numbers are stored in a float variable. Floating-point variables approximate a number, which is why the numbers are almost what you want, but not quite. Maybe using double would give you the precision you need?
Don't use floats when you need absolute exactness. For this use ints and the % operator, then reverse the string.
Thanks ppl.
The % and int is really well thought.
But without major changes on the code using double instead of float completely solves it.

Happy holidays. =)
Topic archived. No new replies allowed.