C++ printf输出格式与if语句教程

一、printf输出格式

1. 基本介绍

学习语言最好的方式就是实践,每当掌握一个新功能时,就要立即将这个功能应用到实践中。

注意:使用printf时最好添加头文件 #include <cstdio>

基础示例

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    printf("Hello World!");

    return 0;
}

2. 不同数据类型的输出格式

格式说明符

数据类型 格式符 说明
int %d 整数输出
float %f 默认保留6位小数
double %lf
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;
}

组合输出示例

所有输出的变量均可包含在一个字符串中:

#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;
}

3. 实践练习

练习1:输出菱形

输入一个字符,用这个字符输出一个菱形:

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    char c;
    cin >> c;

    printf("  %c\n", c);
    printf(" %c%c%c\n", c, c, c);
    printf("%c%c%c%c%c\n", c, c, c, c, c);
    printf(" %c%c%c\n", c, c, c);
    printf("  %c\n", c);

    return 0;
}

练习2:时间转换

输入一个整数,表示时间,单位是秒。输出一个字符串,用"时:分:秒"的形式表示这个时间。

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int t;

    cin >> t;

    int hours = t / 3600;
    int minutes = t % 3600 / 60;
    int seconds = t % 60;

    printf("%d:%d:%d\n", hours, minutes, seconds);

    return 0;
}

4. 扩展功能

(1) 控制小数位数

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;
}

(2) 最小数字宽度控制

a. 前补空格

%8.3f 表示这个浮点数的最小宽度为8,保留3位小数,当宽度不足时在前面补空格。

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int a = 3;
    float b = 3.12345678;
    double c = 3.12345678;

    printf("%5d\n", a);
    printf("%8.4f\n", b);
    printf("%7.3lf\n", c);

    return 0;
}
b. 后补空格

%-8.3f 表示最小宽度为8,保留3位小数,当宽度不足时在后面补上空格

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int a = 3;
    float b = 3.12345678;
    double c = 3.12345678;

    printf("%-5d!\n", a);
    printf("%-8.4f!\n", b);
    printf("%-7.3lf!\n", c);

    return 0;
}
c. 前补0

%08.3f 表示最小宽度为8,保留3位小数,当宽度不足时在前面补上0

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    int a = 3;
    float b = 3.12345678;
    double c = 3.12345678;

    printf("%05d\n", a);
    printf("%08.4f\n", b);
    printf("%07.3lf\n", c);

    return 0;
}


总结要点

printf格式化输出

  • 掌握不同数据类型的格式符(%d, %f, %lf, %c)
  • 学会控制小数位数(%.nf)
  • 理解宽度控制(%width.precisionf)
  • 掌握对齐方式(默认右对齐,-左对齐,0补零)

if条件语句

  • 理解条件判断的基本语法
  • 掌握if-else结构
  • 学会嵌套if语句
  • 能够解决实际问题(比较大小、求绝对值等)

实践建议

  • 多练习格式化输出,提高输出美观度
  • 通过条件语句练习逻辑思维
  • 将printf和if语句结合使用,解决更复杂的问题

0 条评论

目前还没有评论...