介绍
在本实验中,我们将学习如何使用 C 编程语言编写一个程序来计算给定数字的各位数字之和。
注意:你需要自己创建文件
~/project/main.c
来练习编码,并学习如何使用 gcc 编译和运行它。
cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main
在本实验中,我们将学习如何使用 C 编程语言编写一个程序来计算给定数字的各位数字之和。
注意:你需要自己创建文件
~/project/main.c
来练习编码,并学习如何使用 gcc 编译和运行它。
cd ~/project
## 创建 main.c
touch main.c
## 编译 main.c
gcc main.c -o main
## 运行 main
./main
在这一步中,我们将定义三个变量:n
、sum
和 remainder
。我们将使用 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 循环来完成计算。