数字的总和 (c)

编程入门 行业动态 更新时间:2024-10-27 02:30:16
本文介绍了数字的总和 (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)

本文发布于:2023-11-30 12:21:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1649929.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   数字

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!