c - 数字的总和 (c)
问题描述
我需要找到一个五位数的数字之和。例如,数字的位数之和3709
为3 + 7 + 0 + 9 = 19
。
#include <stdio.h>
int main()
{
int sum;
char digit_1, digit_2, digit_3, digit_4, digit_5;
printf("Plase enter a five digit number\n");
scanf("%c,%c,%c,%c,%c", &digit_1, &digit_2, &digit_3, &digit_4, &digit_5);
sum = digit_1 + digit_2 + digit_3 + digit_4 + digit_5;
printf("the sum of the digits is: %d", sum);
return 0;
}
输出:
plase enter a five digit number
3709
the sum of the digits is 51
出于某种原因,它没有显示正确答案,我似乎找不到什么问题。
解决方案
这适用于许多数字;
#include<stdio.h>
int main()
{
int n,digit,sum=0;
printf("Please gine a positive integer");
scanf("%d",&n);
while (n>0)
{
digit=n%10;
sum=sum+digit;
n=n/10;
}
printf("%d",sum);
}
推荐阅读
- javascript - 正则表达式只允许汉字不允许字母字符
- reactjs - 状态改变时对话框播放动画
- java - 如何在 Java 的 TensorFlow 模型中提供稀疏占位符
- flutter - 屏幕不显示颤动
- powershell - 记录cmd.exe的命令行
- apache-spark - Spark Dataframe 中的嵌套数据透视表
- angular7 - Angular http 获取 Date 属性的错误数据类型
- python - 为什么在将 LAB 空间图像写入目录时出现黑色图像?
- c# - c# GUI 在启动控制台应用程序后冻结
- java - android Draw Text with text size change and translate in canvas