[英]C# Sum of digits of a number if the sum equals 9
i want all the numbers with 3 digits that have the sum of 9 to be write in the console. 我想在控制台中写入所有3位具有9之和的数字。 This is what i came up so far and it doesnt work: 这是我到目前为止提出的,它不起作用:
class Program
{
static void Main(string[] args)
{
int sum = 0;
for (int n = 100; n < 1000; n++)
{
while (n <1000)
{
sum += n % 10;
n /= 10;
if (sum == 9)
Console.WriteLine(sum);
}
}
}
}
I'd use three loops, one for every digit: 我会使用三个循环,每个数字一个循环:
for (int i1 = 1; i1 < 10; i1++)
for (int i2 = 0; i2 < 10; i2++)
for (int i3 = 0; i3 < 10; i3++)
{
if (i1 + i2 + i3 == 9)
Console.WriteLine("{0}{1}{2}", i1, i2, i3);
}
You're not resetting sum after every loop iteration. 您无需在每次循环迭代后重设总和。 sum should equal zero at the start of every iteration like. 在每次迭代开始时,总和应等于零。 Also, the while loop is wrong. 另外,while循环是错误的。 Try this: 尝试这个:
for(int n=100;n<1000;n++)
{
sum=0;
int i = n;
while(i!=0) {
sum += i % 10;
i /= 10;
}
if (sum == 9)
Console.WriteLine("Number {0} has digit sum of {1}", n, sum);
}
Why soo commplicated? 为什么这么复杂?
for (int n = 100; n < 1000; n++)
{
var s1 = n/100 % 10;
var s2 = n/10 % 10;
var s3 = n/1 % 10;
var sum = s1+s2+s3;
if (sum == 9)
Console.WriteLine(n);
}
For people, who dont like easy way :D 对于不喜欢简单方法的人:D
Enumerable.Range(0, 1000).Select(x => x.ToString())
.Where(x => x.Length == 3).Select(x => new {x, sum=x.ToCharArray()
.Select(c=>int.Parse(c.ToString())).Sum()}).Where(x=>x.sum == 9)
.Select(x=>x.x).ToList().ForEach(Console.WriteLine);
Oki, tried to create non-generic but fastest solution. Oki尝试创建非通用但最快的解决方案。
for (var i = 1; i <= 10; i++)
for (var j = 0; j < 10; j++)
{
if ((i>1 && j == 0) || i < j)
{
Console.WriteLine(i * 90 + j * 9);
}
}
I think you are looking for this: 我认为您正在寻找:
class Program
{
static void Main(string[] args)
{
for (int n = 100; n < 1000; n++)
{
int sum = 0;
int num = n;
while (num != 0)
{
int r = num % 10;
sum += r;
num /= 10;
}
if (sum == 9)
Console.WriteLine(n);//.....Number whose all digit sum ==9
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.