数字位数之和计算

CCBeginner
立即练习

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

介绍

在本实验中,我们将学习如何使用 C 编程语言编写一个程序来计算给定数字的各位数字之和。

注意:你需要自己创建文件 ~/project/main.c 来练习编码,并学习如何使用 gcc 编译和运行它。

cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL c(("`C`")) -.-> c/BasicsGroup(["`Basics`"]) c(("`C`")) -.-> c/ControlFlowGroup(["`Control Flow`"]) c(("`C`")) -.-> c/UserInteractionGroup(["`User Interaction`"]) c/BasicsGroup -.-> c/variables("`Variables`") c/BasicsGroup -.-> c/operators("`Operators`") c/ControlFlowGroup -.-> c/while_loop("`While Loop`") c/UserInteractionGroup -.-> c/user_input("`User Input`") c/UserInteractionGroup -.-> c/output("`Output`") subgraph Lab Skills c/variables -.-> lab-123338{{"`数字位数之和计算`"}} c/operators -.-> lab-123338{{"`数字位数之和计算`"}} c/while_loop -.-> lab-123338{{"`数字位数之和计算`"}} c/user_input -.-> lab-123338{{"`数字位数之和计算`"}} c/output -.-> lab-123338{{"`数字位数之和计算`"}} end

定义变量并从用户获取输入

在这一步中,我们将定义三个变量:nsumremainder。我们将使用 scanf() 函数从用户获取输入,并将其存储在变量 n 中。

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    // code for sum of digits

    return 0;
}

计算数字的各位数之和

在这一步中,我们将使用一个 while 循环来计算给定数字的各位数之和。

while(n != 0)
{
    remainder = n % 10;
    sum += remainder;
    n = n / 10;
}

上述代码使用取模运算符 (%) 来获取数字除以 10 的余数。这个余数被加到变量 sum 中。然后我们将数字除以 10 以移除其最后一位数字。我们重复这个过程,直到数字变为零。

显示计算结果

在这一步中,我们将使用 printf() 函数向用户显示上面计算出的各位数之和。

printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");

编写完整程序

现在,我们将结合上述所有步骤,编写一个完整的程序来计算一个数字的各位数之和。

#include<stdio.h>

int main()
{
    int n, sum = 0, remainder;

    printf("\n\n\t\tLabEx - Best place to learn\n\n\n");

    printf("Enter the number you want to add digits of:  ");
    scanf("%d", &n);

    while(n != 0)
    {
        remainder = n % 10;
        sum += remainder;
        n = n / 10;
    }

    printf("\n\nSum of the digits of the entered number is  =  %d\n\n", sum);
    printf("\n\n\n\n\t\t\tCoding is Fun !\n\n\n");

    return 0;
}

总结

在本实验中,我们学习了如何使用 C 编程语言编写一个程序来计算给定数字的各位数之和。我们使用了取模运算符和 while 循环来完成计算。

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