2

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

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
user3021170
  • 35
  • 1
  • 1
  • 4

5 Answers5

4

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;
 }
APan
  • 364
  • 1
  • 10
1

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.

fuesika
  • 3,280
  • 6
  • 26
  • 34
1

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?

Community
  • 1
  • 1
IllusiveBrian
  • 3,105
  • 2
  • 14
  • 17
  • doesn't converting a negative float to an int take the ceiling rather than floor? I thought it was truncate towards zero. – Rick Jun 02 '22 at 11:45
0

The conversion to int after dividing will be handled implicitly, no need to cast:

result = b/a;
Wooble
  • 87,717
  • 12
  • 108
  • 131
0

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483