c++用std::cout和printf打印double后面保留几个0?
默认情况下,std::cout打印double不会打印额外的0,printf用%f打印double会保留6个0。
可以用一些设置来控制std::cout和printf默认保留的小数位数。
std::setprecision是 C++ 中< iomanip>头文件提供的一个操纵符,用于设置输出流的精度。它可以用来控制浮点数输出时小数点后的位数。例如,std::setprecision(2)控制double输出小数点后2位,std::setprecision(6)控制double输出小数点后6位。
printf可以使用%.Nf格式化字符串:其中 N 是一个小数点后的位数。例如,%.2f控制double输出小数点后2位,%.6f控制double输出小数点后6位。
下面展示一个具体的例子。
#include <cstdio>
#include <iostream>
#include <iomanip> // 包含 setprecision
int main() {
int i = 10;
double d = 10.0;
double di = static_cast<double>(i); // int 转换为 double
double dx = d/3;
std::cout << "default std::cout:" << std::endl;
std::cout << "i: " << i << std::endl;
std::cout << "d: " << d << std::endl; // std::cout打印double默认不显示后面的无效0
std::cout << "di: " << di << std::endl; // std::cout打印double默认不显示后面的无效0
std::cout << "dx: " << dx << std::endl;
std::cout << "default printf:" << std::endl;
printf("i:%d\n",i);
printf("d:%f\n",d);
printf("di:%f\n",di);
printf("dx:%f\n",dx);
std::cout << std::fixed << std::setprecision(2);
std::cout << "std::setprecision(2) std::cout:" << std::endl;
std::cout << "i: " << i << std::endl;
std::cout << "d: " << d << std::endl;
std::cout << "di: " << di << std::endl;
std::cout << "dx: " << dx << std::endl;
std::cout << "%.Nf printf:" << std::endl;
printf("i:%d\n",i);
printf("d:%.2f\n",d);
printf("di:%.2f\n",di);
printf("dx:%.2f\n",dx);
return 0;
}
将上面代码保存后编译,打印输出如下: