Question

As I understand from Left shift Float type one cannot use left shift operator on float values. But when I tried it, it gave the same answer as multiplying by 2n.

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    // your code goes here
    float a  = 1.1234;
    int b = (int)(a*(1<<10));
    int c = (int)(a*pow(2,10));
    cout << "\n a = " << a << " b = " << b << " c = " << c;
    return 0;
}

It outputs a = 1.1234 b = 1150 c = 1150

In which case will the two outputs (b and c) differ?

Was it helpful?

Solution

int b = (int)(a*(1<<10));

Here, since both 1 and 10 are integers, you are performing left shift operation on integer instead of on floating-point number.

OTHER TIPS

you are multiplying 1024 with value of a(1.1234) in both case. it does not mean you are shifting float value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top