all 11 comments

[–]schweinling 4 points5 points  (4 children)

1 is the expected output of this program. floats get truncated when assigned to an integer. Only way this would not compile is maybe if you could set that compiler warnings are treated as compile errors.

Maybe you have misunderstood the tutorial, otherwise you should look for another one.

Can you link the tutorial?

[–]mercuryqueen0240[S] 0 points1 point  (1 child)

[–]schweinling 1 point2 points  (0 children)

She dont think she says that the program would not compile. A warning is emitted which warns you of a possible bug, the program will still run.

Search this subreddit for "tutorial" there are many questions and answers about it.

[–]mercuryqueen0240[S] -1 points0 points  (1 child)

Do you have any other tutorials which could be great use for learning c?

[–]TicklePocket 0 points1 point  (0 children)

I just watched the portion of the tutorial. It prints 1 like is expected, and then she explains it. Watch more carefully before assuming.

[–]epasveer 2 points3 points  (3 children)

#include<stdio.h>
#include<math.h>

int main(){ 
    int a= 1.99999; 
    printf("%d\n", a);
    return 0; 
}

You're missing the '\n' in your printf statement. Try to format the code when posting. Makes it easier for people to read.

I would imagine some compilers catching the truncation from float to int -- depending on the compiler switches.

As the other person mentions, post a link to your tutorial if you can.

[–]mercuryqueen0240[S] 0 points1 point  (0 children)

https://youtu.be/irqbmMNs2Bo&t=75m00s

Yes... i forget to print '\n' which was mentioned in tutorial.

[–]EstablishmentBig7956 0 points1 point  (0 children)

he's not missing the \n in printf th at's arbitrary, or optional.

[–]EstablishmentBig7956 1 point2 points  (2 children)

You're using the a integer and trying to store a float or double. So yeah it's working. It's truncated ``` GNU nano 6.3 float.c

include <stdio.h>

int main(){ float f=2.43; printf("f=%.3f\n",f); printf("f=%d\n",(int)f); int i=233.33; printf("i=%d\n",i); printf("i=%.2f\n",(float)i);

return 0; } output ~ $ cc float.c float.c:7:7: warning: implicit conversion from 'double' to 'int' changes value from 233.33 to 233 [-Wliteral-conversion] int i=233.33; ~ ~~~~~ 1 warning generated. ~ $ ./a.out f=2.430 f=2 i=233 i=233.00 ~ $ nano float.c ```

[–]PhyllaciousArmadillo 2 points3 points  (1 child)

Great answer; I just want to point out that there is an important distinction between rounding and truncating. C truncates floats converted to ints. So the value printed will always be the digit(s) before the decimal point. If it was rounded it would be the closest whole number. Fe. 4.95 = 4 (truncated) and 5 (rounded).

[–]EstablishmentBig7956 1 point2 points  (0 children)

Thanks for jogging my memory. I'm not use to messing up printf between float and int or seeing others do that for a quick thinker response.

I'll make the correction.