Need help with simple hm

+2 Alex Nueman · February 15, 2015
Hello everyone!

I stuck on understanding of one of my homework question... would appreciate any help.

# include <stdio.h >
int main ()
printf ("3/4 = % f \n " , 3/4);
printf ("3.0/4=% f \n " , 3.0/4);
printf ("1+2/3+0.4=% f \n " , 1+2/3+0.4);

That is the result:

-So in the first line I divided two integers, but I floated them by %f, did not I? Why I get zero with decimal point?
-In the second line it is 3.0, which is a float divided by 4, which is integer, outcome is float... that looks ok for me, because whenever you do operation with different type of values an outcome going to be stored in the type of value, which had the biggest amount of memory reserved for its storage.
-in 3rd line there are no brackets therefore all sequences of operations goes from left to right, right :)? Therefore we get 1,4 and not 2.067. There rule from second example regarding float is applied here as well.

Thank you in advance.

Post a Reply


Oldest  Newest  Rating
+1 Homer Simpson · February 15, 2015
Because 3 and 4 are both integers... So you're doing integer division on them and then displaying them as a float which as we already know will be displayed as 0.0
:] You already explained the rest of the program so I'm assuming you're good on that.
+1 Alex Nueman · February 16, 2015

which as we already know will be displayed as 0.0

Yes, we know that it is going to be 0.0, I can run the program and look on the result and state it, no difficulties here. But I want to know what is going on on background, why instead of 0.750000 I am getting 0.000000.
+2 Lazar Bulic · February 16, 2015
Because your dividing 2 integer values and trying to display them as float you get 0. 3 is an int and  4 is an int. Try casting one of them to float for example add this (float)4/3
+1 Homer Simpson · February 16, 2015
Let me let you in on a little secret... The computer sees everything as numbers. So when you tell C to do something like this.

char notanint = 'a';
printf("%d", notanint);

It will happily display the ascii value for the letter a which is 97. That's all printf does. Display a value in a certain format. 
So you know in integer division 3/4 = 0 already. So what your telling printf to do is display that number as a float. That's why you get 0. Printf doesn't typecast things for u. 
+1 Alex Nueman · February 16, 2015
Okay, I got it, thank you guys.
  • 1



One of the most popular languages of all time.

Bucky Roberts Administrator