【C++入门】(二)printf语句与判断结构
一. printf输出格式
- 注意:使用 printf 时最好添加头文件 #include <cstdio>
#include <iostream> #include <cstdio> using namespace std; int main() { printf("Hello World!"); return 0; }
1.1 int、float、double、char等类型的输出格式
- int:%d
- float: %f, 默认保留6位小数
- double: %lf, 默认保留6位小数
- char: %c, 回车也是一个字符,用'\n'表示
#include <iostream> #include <cstdio> using namespace std; int main() { int a = 3; float b = 3.12345678; double c = 3.12345678; char d = 'y'; printf("%d\n", a); printf("%f\n", b); printf("%lf\n", c); printf("%c\n", d); return 0; }
1.2 所有输出的变量均可包含在一个字符串中
#include <iostream> #include <cstdio> using namespace std; int main() { int a = 3; float b = 3.12345678; double c = 3.12345678; char d = 'y'; printf("int a = %d, float b = %f\ndouble c = %lf, char d = %c\n", a, b, c, d); return 0; }
1.3 扩展功能
- float, double等输出保留若干位小数时用:%.4f, %.3lf
#include <iostream> #include <cstdio> using namespace std; int main() { float b = 3.12345678; double c = 3.12345678; printf("%.4f\n", b); printf("%.3lf\n", c); return 0; }
- 最小数字宽度
- %8.3f, 表示这个浮点数的最小宽度为8,保留3位小数,当宽度不足时在前面补空格
- %-8.3f,表示最小宽度为8,保留3位小数,当宽度不足时在后面补上空格
- %08.3f, 表示最小宽度为8,保留3位小数,当宽度不足时在前面补上0
二. if 语句
2.1 基本if-else语句
#include <iostream> using namespace std; int main() { if (判断条件) { } else { } return 0; }
else 语句可以省略,变成下面这样:
#include <iostream> using namespace std; int main() { if (判断条件) { } return 0; }
当只有一条语句时,大括号可以省略:
#include <iostream> #include <cstdio> using namespace std; int main() { if (判断条件) printf("执行条件"); else printf("执行条件"); return 0; }
2.2 常用比较运算符
- 大于 >
- 小于 <
- 大于等于 >=
- 小于等于 <=
- 等于 ==
- 不等于 !=
2.3 if-else 多条件
#include <iostream> using namespace std; int main() { if (判断条件1) { } else if (判断条件2) { } else if (判断条件3) { } else { } return 0; }
三. 条件表达式
- 与 &&
- 或 ||
- 非 !

浙公网安备 33010602011771号