我请问一下,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是没有的,多余的。。。
我请问一下,C语言 任意输入一个数,把各个数字分开,然后相加,怎么做?
数可能两位可能三位可能四位。。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
2024-10-15 04:00:41
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上,然后去掉个位,十位变个位,反复加直到最后只剩个位。出循环后再加一下就行了