|Can someone explain displaying floating point values?
|Page 1 of 1|
|Author:||JamesD [ Tue Feb 20, 2007 8:01 am ]|
|Post subject:||Can someone explain displaying floating point values?|
I'm having a bit of trouble displaying floating point values that make sense.
Can anyone explain why the code below is displaying the following:
Does the display show decimals? Why doesn't the display show
PI= 3.142 etc
|Author:||JamesD [ Wed Feb 21, 2007 9:44 pm ]|
To answer my own email in the interest of others who may follow.
To correctly display floating point variables you need to define how many decimal points you want displayed in the format shown below.
Another thing to note is that, in order for x to be a decimal/floating point the 180 needs to be written as 180.0 (otherwise x displays 0). Is this intentional? Is it a convention of C based languages? This took me quite a while to work out.
|Author:||Dick Swan [ Mon Feb 26, 2007 5:01 am ]|
Regarding evaluating the equation "x = 60 / 180;" where 'x' is a 'float' variable. This is the behavior of the standard C language. Here's what is happening:
So when you changed '180' to '180.0', the compiler then did the calculations using floating point arithmetic and you get the desired results of 0.3333.
You'd get the same original results if the code was.
int i = 60;
int j = 180;
x = i/j;
There is a way to force the compiler to use floating point arithmetic in the above. You use a "cast" statement which converts one 'type' to another. The last line above would be replaced with
x = i / (float) j;
The "(float)" is a 'cast' modifier which says convert the expression to the right to a 'float' value. There's a lot more powerful things that you can do with 'cast' but can't be covered here.
|Author:||JamesD [ Tue Feb 27, 2007 6:52 am ]|
Thank you for elaborating on this topic. Very helpful.
|Author:||Miguel Angel [ Fri Mar 16, 2007 11:14 pm ]|
|Post subject:||Re: Can someone explain displaying floating point values?|
Just change %d for %f in your code, I think it will work.
|Page 1 of 1||All times are UTC - 5 hours [ DST ]|
|Powered by phpBB © 2000, 2002, 2005, 2007 phpBB Group