c++static-cast

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.


Solution

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