3.8 floatnum.cpp
#include <iostream>
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield);
float tub = 10.0 / 3.0;
double mint = 10.0 / 3.0;
const float million = 1.0e6;
cout << "tub = " << tub;
cout << ", a million tubs = " << million * tub;
cout << ",\nand ten million tubs = ";
cout << 10 * million * tub << endl;
cout << "mint = " << mint << " and a million mints = ";
cout << million * mint << endl;
// cin.get();
return 0;
}
- 该函数主要演示了float类型和double类型的验算以及精度
- 用乘以million的方法使程序显示小数点后六位
- 从结果来看double的精度要高于float
3.9 fltadd.cpp
#include <iostream>
int main()
{
using namespace std;
float a = 2.34E+22f;
float b = a + 1.0f;
cout << "a = " << a << endl;
cout << "b - a = " << b - a << endl;
return 0;
}
- 该函数主要探究float类型的精度问题
- 后缀为f,代表其为float类型
- b-a结果为0,证明float类型运算精度低
3.10 arith.cpp
#include <iostream>
int main()
{
using namespace std;
float hats, heads;
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << "Enter a number: ";
cin >> hats;
cout << "Enter another number: ";
cin >> heads;
cout << "hats = " << hats << "; heads = " << heads << endl;
cout << "hats + heads = " << hats + heads << endl;
cout << "hats - heads = " << hats - heads << endl;
cout << "hats * heads = " << hats * heads << endl;
cout << "hats / heads = " << hats / heads << endl;
return 0;
}
- 该函数主要探究float类型之间运算的问题
- ios_base::fixed代表使用定点计数法,如1234.5(与科学计数法相对应,如1.2345e4)
- ios_base::floatfield代表输出到小数点后6位。
- 由于float计算精度有限,所以c++只保证6为有效位,所以以下奇怪的结果需要将其四舍五入至六位,如45.509998需看做45.5100
3.11 divide.cpp
#include <iostream>
int main()
{
using namespace std;
cout.setf(ios_base::fixed, ios_base::floatfield);
cout << "Integer division: 9/5 = " << 9 / 5 << endl;
cout << "Floating-point division: 9.0/5.0 = ";
cout << 9.0 / 5.0 << endl;
cout << "Mixed division: 9.0/5 = " << 9.0 / 5 << endl;
cout << "double constants: 1e7/9.0 = ";
cout << 1.e7 / 9.0 << endl;
cout << "float constants: 1e7f/9.0f = ";
cout << 1.e7f / 9.0f << endl;
return 0;
}
- 此代码探究不同类型下数字相除的结果
- 首先是整数部分,9/5得到整数1,小数部分舍弃
- 之后两行表明,无论是9.0/5.0还是9.0/5,只要有一个操作数是浮点数,结果都为浮点数,这涉及到c++的类型转换,之后也有例子
- 之后输出表明c++默认浮点常量为double类型,两个都是double类型操作数,运算结果为double,两个都是float,结果为float类型