首页 > 解决方案 > 数字的总和 (c)

问题描述

我需要找到一个五位数的数字之和。例如,数字的位数之和37093 + 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

出于某种原因,它没有显示正确答案,我似乎找不到什么问题。

标签: csum

解决方案


这适用于许多数字;

#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);
}

推荐阅读