Naresh
Naresh

Reputation: 344

How to type cast int division to floating point?

#include <iostream>
#include <stdio.h>
using namespace std;
 
int main() {
 
 float f=static_cast<float>(5/2);
 printf("%f",f);
 
 return 0;
}

The answer is always 2.0. I searched before asking but couldn't find the answer.

Upvotes: 1

Views: 11232

Answers (3)

jack
jack

Reputation: 2204

int main() {

    float f = 5.0 / 2;
    printf("%f", f);
    return 0;
}

Upvotes: 1

bogdan
bogdan

Reputation: 9317

You just need to do

float f = 5.0f / 2;

In your code, 5 and 2 are ints, so in 5/2 the / operator is the integer division operator; the result will always be an integer, in this case, 2. Only then is it converted to float, giving 2.0.

You need to do floating point division, so at least one of the operands needs to be of floating point type. You could just write 5.0, without the f, but that would have type double by default, and the result will then be converted to float - a conversion that can cause issues (not here for these particular constant values, but still, it's better to use the right type in the first place).

Upvotes: 4

Irrational Person
Irrational Person

Reputation: 550

This works on my compiler:

#include <iostream>
#include <stdio.h>
using namespace std;

int main() {

 float f=(float)5/(float)2;
printf("%f",f);

return 0;
}

Upvotes: 0

Related Questions