作业帮 > 综合 > 作业

从键盘上输入任意一个整数x,编程计算x的每一位数字相加之和,用C语言编写,下面我编写的程序哪错了

来源:学生作业帮 编辑:拍题作业网作业帮 分类:综合作业 时间:2024/05/01 13:58:29
从键盘上输入任意一个整数x,编程计算x的每一位数字相加之和,用C语言编写,下面我编写的程序哪错了
例如,输入x为1234,则分离出1,2,3,4四个数字,然后计算1+2+3+4=10,并输出10,
#include
#include
void main()
{
\x09int n=0;
\x09while("getchar()"!="\n")
\x09{
\x09\x09n+=getchar();
\x09\x09
\x09}
\x09printf("%d",n);
\x09system("pause");
}
/>

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int n=0;
    char ch;

    while((ch=getchar())!='\n')
    {
        n+=ch-'0';
    }
    printf("%d\n",n);
    system("pause");
}
再问: ch-'0'是什么意思
再答: ch为char类型,假设是'6'ch-'0'等于6,也就是通常说的六.