Reputation: 35
I have been trying to get an integer value when dividing float by integer , but I could not come up with what I am looking for .
int a = 3 ;
float b = 15.50 ;
int result ;
result = int b/a
I have not programmed for long time , and I know this is basic and I should be aware of it , I really appreciate any help . Thank you
Upvotes: 2
Views: 21329
Reputation: 234875
Let's first correct the last line to
result = (int) b / a;
But that causes surprising behaviour: The (int)
cast has higher precedence than /
, so b
is converted to an int
(will truncate to 15) before it's divided by a
.
The upshot of this is that b / a
is performed in integer arithmetic: 15 / 3
. The effect is fairly benign as this division has no remainder, but if b
was, say, 16.5 then you'd notice the effects. Try it!
Dropping the errant cast; i.e.
result = b / a;
will mean that the division will be performed in floating point (a
gets promoted) and that gets converted to an int
type.
Upvotes: 0
Reputation: 366
The compiler automatically casts the type to the type of the left hand side operand of the assignment operator. In this case its of type int, so the result will be converted in to int implicitly. You don't have to type-cast explicitly
#include<stdio.h>
int main()
{
int a = 3 ;
float b = 15.50 ;
int result ;
result = b/a; // automatic type promotion of a to float so b/a = 5.1666666666
//but due to implicit type casting 5.16666 truncated to 5
printf("%d",result); // 5 will be printed.
return 0;
}
Upvotes: 4
Reputation: 90037
The conversion to int after dividing will be handled implicitly, no need to cast:
result = b/a;
Upvotes: 0
Reputation: 3234
Generally casting the result to an integer will give you the floor of the result, but if you are looking for a rounded result you will probably need to use something like the solution here:
How to round floating point numbers to the nearest integer in C?
Upvotes: 1
Reputation: 3330
You define result to be an integer:
int result;
This forces the result of b/a to be an integer. In case this is what you intended: cast the result of b/a to integer and store it in result:
result = (int)floor(b/a);
Use floor
(or ceil
) for well-defined results in result and clear and concise code.
Upvotes: 2