【情景描述】
某一个整数位数不足,需要补0。如“a = 7”,要求输出“007”;又如“b = 28”,要求输出“0028”。
【解决方法】
1.C语言
1.1 头文件:<stdio.h>
#include<stdio.h>
1.2 输出方法
①错误示范:
#include<stdio.h>
int main() {
int a = 1;
printf("%8d", a);//输出8位数值
return 0;
}
输出结果:
_______1
//下划线'_'代表空格' ',结尾即为7个空格' '+'1'
这种情况不能满足“补足0”的要求。
②正确示范:
#include<stdio.h>
int main() {
int a = 1;
printf("%08d", a);//输出8位数值,以'0'补足
return 0;
}
输出结果:
00000001
满足题目需求。
2.C++
2.1 头文件:<iomanip>
#include<iomanip>
2.2 输出方式
①函数:setw(int n)
作用:确定需要补足位数
#include<iomanip>
int main() {
int a = 1;
cout << setw(3) << a;//输出三位数值
return 0;
}
输出结果:
__1
//下划线'_'代表空格' ',结尾即为2个空格' '+'1'
②函数:setfill(char c)
作用:确定用于补足的字符
#include<iomanip>
int main() {
int a = 1;
cout << setw(3) << setfill('0') << a;//输出三位数值,字符'0'用于补足
return 0;
}
输出结果:
001
【总结】
C++语言
头文件:<iomanip>
函数:setw(int n)//确定需要补足位数
函数:setfill(char c)//确定补足的字符
cout << setw(8) << setfill('0') << 1 << endl;//用'0'字符补足8位
输出:00000001
//可以设置其他字符补足
C语言
头文件:<stdio.h>
printf("%08d \n",1);
输出:00000001