用 C 语言创建乘法表

CCBeginner
立即练习

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

介绍

在本实验中,你将学习编写一个 C 程序,用于打印任意给定数字的乘法表。该程序将接收用户输入的数字,并打印该数字的前 10 个倍数。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/CompoundTypesGroup(["`Compound Types`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/for_loop("`For Loop`") c/CompoundTypesGroup -.-> c/strings("`Strings`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123287{{"`用 C 语言创建乘法表`"}} c/operators -.-> lab-123287{{"`用 C 语言创建乘法表`"}} c/for_loop -.-> lab-123287{{"`用 C 语言创建乘法表`"}} c/strings -.-> lab-123287{{"`用 C 语言创建乘法表`"}} c/user_input -.-> lab-123287{{"`用 C 语言创建乘法表`"}} c/output -.-> lab-123287{{"`用 C 语言创建乘法表`"}} end

创建主函数

#include <stdio.h>

int main()
{
    int n, i;

    printf("Enter an integer you need to print the table of: ");
    scanf("%d", &n);

    printf("\nMultiplication table of %d:\n", n); // 打印表格标题

    // 乘法逻辑
    for (i = 1; i <= 10; i++)
        printf("%d x %d = %d\n", n, i, n * i);

    return 0;
}

在上述代码中,我们创建了主函数,该函数接收用户输入的整数 n 并打印给定数字的乘法表。

获取用户输入

int n;

printf("Enter an integer you need to print the table of: ");
scanf("%d", &n);

在上述代码中,我们获取用户输入的整数值并将其存储在名为 n 的变量中。我们使用 scanf 函数来读取输入值。

打印乘法表标题

printf("\nMultiplication table of %d:\n", n);

我们使用上述代码来打印乘法表的标题。我们使用了 \n 来添加换行符以提高可读性。

乘法逻辑

for (i = 1; i <= 10; i++)
    printf("%d x %d = %d\n", n, i, n * i);

在这一步中,我们使用了一个 for 循环来打印给定数字的前十个倍数。我们将数字 n 与计数器变量 i 相乘,并使用 printf 函数打印结果。

最终程序代码

将以下最终程序代码复制并粘贴到 ~/project/ 目录下的 main.c 文件中:

#include <stdio.h>

int main()
{
    int n, i;

    printf("Enter an integer you need to print the table of: ");
    scanf("%d", &n);

    printf("\nMultiplication table of %d:\n", n); // 打印表格标题

    // 乘法逻辑
    for (i = 1; i <= 10; i++)
        printf("%d x %d = %d\n", n, i, n * i);

    return 0;
}

总结

在本实验中,你学习了如何打印任意给定数字的乘法表。我们创建了一个程序,该程序接收用户输入,打印表格标题,然后使用乘法逻辑显示输入数字的前十个倍数。通过遵循这个逐步指南,你现在可以用 C 语言创建自己的乘法表程序。

您可能感兴趣的其他 C 教程