Like the title, integers can use bit operations, how to solve floating point numbers? Due to the word limit of the title, the original text is how to calculate the average of two float point numbers without operator /
?
代言2017-07-03 11:43:47
Thanks for the invitation.
float x = 1.1;
float y = 1.2;
int * xx = (int*)&x;
int * yy = (int*)&y;
int k = (*xx + *yy) >> 1;
float * kk = (float*)&k;
cout << *kk << endl; // 1.15 ,结果正确
I used double at first, but the output overflowed. I suddenly thought that on my computer (most computers) double is 8 bytes, and int is only 4 bytes, so just change double to float.
There are no difficulties in the code. The only one I guess is the conversion of integers and floating point numbers in binary. You will know this part if you have studied computer composition, IEEE floating point representation.
代言2017-07-03 11:43:47
average = (a + b) * 0.5;
Off topic,
I feel like this question is actually not a programming question, it should be a brain teaser~