c++ - the average of two float point numbers without operator/?

浏览:33日期:2023-03-14

问题描述

如题, 整数可以用位运算, 浮点数该怎么解决? 受标题字数限制, 原文是 how to calculate the average of two float point numbers without operator / ?

问题解答

回答1:

谢邀。

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 ,结果正确

起初用的double,输出溢出了,突然想到我的电脑下(大多数电脑)double是8字节,int只有4字节,所以把double换成float就可以了。

代码没有难点,唯一一个我估计就是整数与浮点数在二进制上转换,这部分你学过计算机组成就知道了,IEEE浮点表示法。

回答2:

average = (a + b) * 0.5;

题外话,感觉其实这题不是程序设计题,应该是脑筋急转弯啊~

相关文章: