C++ Primer Plus P49 程序清单3.9(float精度小导致的计算问题)——中职

C++ Primer Plus P49 程序清单3.9

float精度小导致的计算问题

/*
C++ Primer Plus P49 程序清单3.9
float精度小导致的计算问题
*/

//头文件
#include<iostream>

//主函数
int main(void)
{
    
    
	using namespace std;

	/*float表示*/
	cout << "float表示:" << endl;
	float a = 2.34E+22;
	float b = a + 1.0;

	cout << "a = " << a << endl;
	cout << "b = " << b - a << endl;
	
	return 0;
}

//依照题意本应该b - a = 1,但结果为0,因为a + 1.0是加在小数点右边第23未的数字(即234000....01.000000),因为float精确为只有6位所以结果为0

这里注意对比:
float表示

	float a = 2.34E+22;
	float b = a + 1.0;

	cout << "a = " << a << endl;
	cout << "b = " << b - a << endl;

依照题意本应该b - a = 1,但结果为0,因为a + 1.0是加在小数点右边第23未的数字(即234000…01.000000),因为float精确为只有6位所以结果为0。

感谢观看

再次感谢~

猜你喜欢

转载自blog.csdn.net/qq_51212951/article/details/113370325
今日推荐