数字的总和 (c) [英] digits sum of a number (c)

查看:51
本文介绍了数字的总和 (c)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要找到一个五位数的数字之和.例如,数字3709的数字之和为3 + 7 + 0 + 9 = 19.

I need to find the sum of the digits of a number with five digits. For example, the sum of the digits of the number 3709 is 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

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

For some reason it doesn't show to correct answer and i can't seem to find whats wrong.

推荐答案

你的代码有问题

你的 scanf 需要 , 分开的输入

your scanf needs , separated inputs

scanf("%c,%c,%c,%c,%c", ...)

因此,当您输入 3709 时,只会读取 digit1 而其余的将被 scanf 忽略.可以查看scanf的返回值进行验证.

Hence when you enter 3709 only digit1 will be read and rest will be omitted by scanf. You can check the return value of scanf to verify.

3 的 ASCII 值是 51 因此你得到 51 作为输出.

and ASCII value of 3 is 51 thus you are getting 51 as output.

试试这个

scanf("%c%c%c%c", &digit_1 ,&digit_2 ,&digit_3 ,&digit_4 );

int sum = (digit_1 -'0')+(digit_2 -'0')+(digit_3 -'0')+(digit_4 -'0');

这篇关于数字的总和 (c)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆