笔者使用的编译器保证了C++中float类型至少在6个有效位上是计算精确的(double为15位)。源码摘自《C++ Primer Plus》,有微小改动。
#include <iostream>
using namespace std;
int main() {
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;
return 0;
}
Output:
tub = 3.333333, a million tubs = 3333333.250000,
and ten million tubs = 33333332.000000
mint = 3.333333and a million mints = 3333333.333333
float在6位之后有效位不在是计算精确的,而duoble在13位时仍然保证计算的精确性。