C/C++输入和输出

阅读量: 213 编辑

C语言格式化输出

//爱码岛编程

//头文件
#include <cstdio>

//输出100
int a = 100; 
printf("%d", a); 

//输出20000
long long a = 20000;
printf("%lld", a);  

//输出浮点数,3.1415926
float a = 3.1415926;
printf("%f", a);     

//保留3位小数输出,3.142
float a = 3.1415926;
printf("%.3f", a);  

//输出双精度类型,0.33333
double a = 1.0/3;
printf("%lf", a);

//保留3位小数,输出双精度类型,0.333
double a = 1.0/3;
printf("%.3lf", a); 

//输出字符类型 A
char ch = 'A';
printf("%c", ch);

//输出字符串数组 hello
char arr[10] = "hello";
printf("%s", arr); 

//输出宽度为5,右对齐,不够补空格  100
int a = 100;
printf("%5d", a);

//输出宽度为5,左对齐,不够补空格。100 
int a = 100;
printf("%-5d", a);

//输出宽度为5,右对齐,不够补0。00100
int a = 100; 
printf("%05d", a);

//无论是正数还是负数,都要把符号输出
int a = -100;
printf("%+d", a);

C++格式化输出

//爱码岛编程

//用函数,保留两位小数
cout.flags(ios::fixed);
cout.precision(2);

//用格式化输出头文件
#include <iomanip>

//保留两位小数
double a = 3.1415926;
cout << setprecision(2) << a << endl;

//输出宽度为5,右对齐,不够补空格。  100
int a = 100;
cout << setw(5) << a ;

//宽度为5,不够用*填充
int a = 100;
cout << setw(5) << setfill('*') << a ;

//左对齐
int a = 100;
cout << left << setw(5);

//右对齐
int a = 100;
cout << right << setw(5);

//正负号
int a = 100;
cout << showpos << a;
爱码岛编程公众号
试卷资料
爱码岛编程小程序
在线刷题
苏ICP备13052010号
©2023 南京匠成信息科技有限公司