C语言 任意输入一个数,把各个数字分开,然后相加,怎么做

我请问一下,C语言 任意输入一个数,把各个数字分开,然后相加,怎么做?

数可能两位可能三位可能四位。。
#include<stdio.h>
int main()
{
int a,s=0,;
scanf("%d",&a);
while(a)
{
s=a%10;
printf("%d\n",s);
a=a/10;
b=s+s;
}
}
我可以用这个把数字分开比如123分成了1,2,3,我怎么把这三个数字加起来?
b=s+s是没有的,多余的。。。
最新回答
著墨染雨君画夕

2024-10-15 06:53:43

你可以再新建一个变量来累加:

#include<stdio.h>
int main()
{
    int a,s=0,k;
    scanf("%d",&a);
    while(a)
    {
       k=a%10;
       printf("%d\n",k);
       a=a/10;
       s=s+k; /*这里是关键,用s变量来累加,注意s一开始要初始化为0*/ 
    }
    printf("%d",s);
}
一清北华

2024-10-15 03:53:00

。。。这个很简单啊。。。你已经都用 s = a%10了。。。那就是求余嘛。。。说明你把每个位都取出来了。

逆向思考下嘛。。。

int countNum = 1;//这句是新增的
while(a)
{
s=a%10;
printf("%d\n",s);
a=a/10;

//注意下面的修改
b += s*pow(10,countNum);
countNum++;
}

如果提示没有pow这个函数,请 #include<math.h>
红颜乱

2024-10-15 04:00:41

//#include "stdafx.h"//vc++6.0加上这一行.
#include "
stdio.h
"
void main(void){
int n,x;
printf("Input an integer...\nn=");
scanf("%d",&n);
for(x=0;n;n/=10)
x+=n%10;
printf("The result is %d.\n",x);
}
步信停云

2024-10-15 06:27:10

#include<stdio.h>
#include<string.h>
#define MAX 40

int main(void)
{
  char shu[MAX];
  int i,tot=0;
  
  printf("请输入一个数:");
  gets(shu);
  for(i=strlen(shu)-1;i>=0;i--)
    tot+=shu[i]-'0'
  printf("这些数字加起来是%d",tot);
  return 0;
}
追问
虽然可以用但是太高档了我还没学啊!现在就会if while for switch。。。可以做吗
追答

我只写关键部分

scanf("%d",&n);
while(n/10!=0)
{
  tot+=n%10;
  n/=10;
}
tot+=n;
printf("数字之和为%d",tot);
刚才没仔细想,现在想下这样是比较简单
追问
。。为什么我在DVC++运行算是不对的呢
追答
先把tot清零,思想就是每次都把个位加到tot上,然后去掉个位,十位变个位,反复加直到最后只剩个位。出循环后再加一下就行了