使用do-while计算正整数num的各位上和
时间: 2024-06-10 09:08:58 浏览: 9
好的,这是一个计算正整数各位数字之和的问题,可以使用do-while循环来实现。首先,我们需要让用户输入一个正整数num,然后通过循环依次取出num的各位数字,并将其累加起来,最后输出结果即可。以下是代码示例:
```
#include <stdio.h>
int main()
{
int num, sum = 0, digit;
printf("请输入一个正整数:");
scanf("%d", &num);
do {
digit = num % 10; // 取出num的个位数字
sum += digit; // 累加到总和中
num /= 10; // 将num缩小10倍,去掉个位数字
} while (num > 0); // 当num还有剩余数字时继续循环
printf("各位数字之和为:%d\n", sum);
return 0;
}
```
希望这个代码示例可以帮到你!
相关问题
c语言计算正整数num 各位上数字之积
以下是两种C语言计算正整数num各位上数字之积的例子:
1.使用do-while循环计算
```c
#include <stdio.h>
long fun(long num) {
long k = 1;
do {
k *= num % 10;
num /= 10;
} while (num);
return k;
}
int main() {
long n;
printf("\nPlease enter a number:");
scanf("%ld", &n);
printf("\n%ld\n", fun(n));
return 0;
}
```
2.使用while循环计算
```c
#include <stdio.h>
int main() {
int i,a,b,c=1;
scanf("%d",&a);
if(a%10==0) {
printf("0\n");
} else {
while(a%10!=0) {
i=(int)a/10;
b=a%10;
a=i;
c=c*b;
}
printf("%d\n",c);
}
return 0;
}
```
C语言计算正整数num的各位上的数字之积
以下是C语言计算正整数num的各位上的数字之积的代码实现:
```c
#include <stdio.h>
long fun(long num) {
long k = 1;
do {
k *= num % 10;
num /= 10;
} while (num);
return k;
}
int main() {
long n;
printf("\nPlease enter a number:");
scanf("%ld", &n);
printf("\n%ld\n", fun(n));
return 0;
}
```
该程序首先定义了一个函数`fun`,该函数的参数为一个正整数`num`,返回值为`num`的各位上的数字之积。在函数中,我们使用了do-while循环来不断地取出`num`的个位数,然后将其乘到变量`k`中,最后将`num`除以10,直到`num`变为0为止。最后,我们在主函数中调用`fun`函数,并输出结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)