C语言中输出时怎样控制小数点后的位数,请举例说明保

如题所述

举例说明如下:

#include <iostream>
#include <iomanip>
using namespace std;

int main( void )
{
const double value = 12.3456789;

cout << value << endl; // 默认以6精度,所以输出为 12.3457
cout << setprecision(4) << value << endl; // 改成4精度,所以输出为12.35
cout << setprecision(8) << value << endl; // 改成8精度,所以输出为12.345679
cout << fixed << setprecision(4) << value << endl; // 加了fixed意味着是固定点方式显示,所以这里的精度指的是小数位,输出为12.3457
cout << value << endl; // fixed和setprecision的作用还在,依然显示12.3457
cout.unsetf( ios::fixed ); // 去掉了fixed,所以精度恢复成整个数值的有效位数,显示为12.35
cout << value << endl;
cout.precision( 6 ); // 恢复成原来的样子,输出为12.3457
cout << value << endl;
}

C语言之所以命名为C,是因为 C语言源自Ken Thompson发明的B语言,而 B语言则源自BCPL语言。

C语言是一种计算机程序设计语言,它既具有高级语言的特点,又具有汇编语言的特点。它由美国贝尔研究所的D.M.Ritchie于1972年推出,1978年后,C语言已先后被移植到大、中、小及微型机上,它可以作为工作系统设计语言,编写系统应用程序,也可以作为应用程序设计语言,编写不依赖计算机硬件的应用程序。它的应用范围广泛,具备很强的数据处理能力,不仅仅是在软件开发上,而且各类科研都需要用到C语言,适于编写系统软件,三维,二维图形和动画,具体应用比如单片机以及嵌入式系统开发。

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-02-26

举例说明如下:

#include <stdio.h>
int main()
{
    double pi=3.1415926456789565;
printf("%.2f\n",pi);  //保留小数点后2位
printf("%.6f\n",pi);  //保留小数点后6位
printf("%.15f\n",pi); //保留小数点后15位
    return 0;
}

运行结果:

3.14

3.141593

3.141592645678957

本回答被网友采纳
第2个回答  2016-11-16
#include<stdio.h>
int main(void){
float i = 12.0;
printf("%f\n", i);
printf("%.1f\n", i);
printf("%.2f\n", i);
printf("%.3f\n", i);
printf("%.4f\n", i);
printf("%.5f\n", i);
printf("%.6f\n", i);
printf("%.7f\n", i);
printf("%.8f\n", i);
printf("%.9f\n", i);
printf("%.10f\n", i);
printf("%.11f\n", i);
printf("%.12f\n", i);

return 0;
}

运行结果:

12.000000

12.0

12.00

12.000

12.0000

12.00000

12.000000

12.0000000

12.00000000

12.000000000

12.0000000000

12.00000000000

12.000000000000

printf("%f\n", i);在普通输出控制格式字符的%和f中间加“.#”(其中#为小数点位数)