C#如何让一个数,个位十位百位 单个相加?

比如 123=1+2+3 ;8988=8+9+8+8;求代码!

123与1+2+3不相等啊,你的意思是把数的每一位相加吧如果数的位数不固定,可以用循环n是数字,s是数字每位相加之和s=0;while(n>0){ s+=n%10; n/=10;}
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2018-08-20
int sum = 0;
int num = 8988;
while (num > 0)
{
sum += num % 10;//每次的余数都是末尾的数字
num /= 10;//因为是INT型的所以等于直接去掉最后的数字.
}
Console.WriteLine(sum);本回答被网友采纳
第2个回答  2013-07-06
如果你觉得答案好的话 请评分并采纳 using System;
using System.Collections.Generic;
using System.Text;namespace test
{
class Program
{
static void Main(string[] args)
{
int sum = 0;
int num = 8988;
while(num>0)
{
sum += num % 10;
num /= 10;
}
Console.WriteLine(sum);
Console.ReadKey();
} }}
第3个回答  2013-07-06
int i=123;int sum=0;while(i%10!=0){sum=sum+(i%10);i=i/10;
} 或者,你把那个数转成字符截取(substring)后再轮换成数相加Console.Write(sum);
第4个回答  2013-07-06
using System;
using System.Collections.Generic;
using System.Text;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int a = 0;
int b = 123;
while (b > 0)
{
a += b % 10;
b /= 10;
}
Console.WriteLine(a);
}
}
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网