getting integer result when dividing float by integer in c

12,200

Solution 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.

Solution 2

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;
 }

Solution 3

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?

Share:
12,200
Admin
Author by

Admin

Updated on June 11, 2022

Comments

  • Admin
    Admin almost 2 years

    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

  • Rick
    Rick almost 2 years
    doesn't converting a negative float to an int take the ceiling rather than floor? I thought it was truncate towards zero.