Visit Jeremy's Blog.
 Home Forums HCL Reviews Tutorials Articles Register Search Today's Posts Mark Forums Read
 LinuxQuestions.org C newbie float ?
 Programming This forum is for all programming questions. The question does not have to be directly related to Linux and any language is fair game.

Notices

 09-02-2003, 08:15 AM #1 bluesky LQ Newbie   Registered: Feb 2003 Posts: 4 Rep: C newbie float ? Hi guys I am a newbie in C programming. When I try the follwoing code, it does not seem right. #include int main (void) { float num = 0.0; num = 3 / 7; printf("---> %f\n", num); return 0; } Somehow it print num is equal to 0.000000. Could someone tell me what is wrong with it. Thank you for your help.
 09-02-2003, 08:45 AM #2 nephilim Member   Registered: Aug 2003 Location: Belgium Distribution: Debian (server), Kubuntu (desktop) Posts: 248 Rep: I think the problem is the line where you assign num = 3 / 7. Since 3 and 7 are integers, your result will also be an integer (in this case 0) which is than cast to a float (0.0). Try this: num = 3.0 / 7.0 and see what the output is.
 09-02-2003, 08:46 AM #3 nephilim Member   Registered: Aug 2003 Location: Belgium Distribution: Debian (server), Kubuntu (desktop) Posts: 248 Rep: In addition to my post above: You can also cast the integers to float yourself, so this could also work: num = (float)3 / (float)7
 09-02-2003, 05:57 PM #4 bluesky LQ Newbie   Registered: Feb 2003 Posts: 4 Original Poster Rep: Thanks alot for your help 3.0 / 7.0 work ^_^ Thanks for your help again
 09-02-2003, 10:19 PM #5 LinuxTiro Member   Registered: Aug 2003 Posts: 59 Rep: u can even give num=(float)3/7; or num=3/(float)7; note:- operation between an int and a real always yields a real.
09-02-2003, 11:01 PM   #6
SaTaN
Member

Registered: Aug 2003
Location: Suprisingly in Heaven
Posts: 223

Rep:
Quote:
 Originally posted by HiTleR u can even give num=(float)3/7; or num=3/(float)7; note:- operation between an int and a real always yields a real.

Everyone has been repeating the same thing which most of us know ..

But, no one has explained why it is that way .

Maybe someonne would give me an answer

 09-03-2003, 12:50 AM #7 jinksys Member   Registered: Aug 2003 Location: 63123 Distribution: OpenSuSE/Ubuntu Posts: 418 Rep: consider the following code. float num; <- defines num as a float. num=1/2; <- in the C world, 1 is different than 1.0 . 1 is an integer, so 1/2 is zero, since 2 doesnt go into 1 at least one time. Now 1.0/2.0 is 0.5 since 1.0 and 2.0 are floats and therefore the arithmatic 1.0/2.0 will return a float number. Now consider this: float num; <- defines float num=(float)1/(float)2; <- (float) is called a type casting. If you dont know what that is, let me explain. Type casting converts one type into another. So this code: int num; float num2; num=5; <- assigns 5 to num. num2= (float)num / (float) 5; <- converts num to a float, 5 to 5.0, and then executes the division, which returns a float. hope that helps