Sum of Digits of a Five Digit Number
任务
输入一个5位数和打印每位数字的和。
解答
使用for
循环语句
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
//Complete the code to calculate the sum of the five digits on n.
int sum=0, i;
for (i=n;i;i/=10){
sum += i % 10;
}
printf("%d", sum);
return 0;
}
使用while
循环语句
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
int main() {
int n;
scanf("%d", &n);
//Complete the code to calculate the sum of the five digits on n.
int sum = 0;
while (n){
sum += n % 10;
n /= 10;
}
printf("%d", sum);
return 0;
}