In C, what is the difference between these two?
float myF = 5.6;
printf( "%i \n", (int)myF ); // gives me "5"
printf( "%ld \n", floor(myF) ); // also "5"?
When is one preferable over the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One big difference is that of negative numbers; if you change
myFto-5.6, then casting to an int returns-5whilefloor(myF)is-6.As to which is preferable, as a rule of thumb I’d say to only cast to an int if you know that’s what you need — and since you’re asking here, chances are that you probably want
floor.(Also note that with
printfformatting,%ldis a long integer; a double is%lf.)