简体   繁体   English

C#中的数字总和

[英]Digit sum in for loop C#

I wrote I method which is suppose to recieve a nubmer from user and then check number from 0 to 1000. Then it should return all number which have digit sum equal to recieved number. 我写了一个方法,该方法假设是从用户那里接收一个数字,然后检查0到1000之间的数字。然后它应该返回所有数字总和等于所接收数字的数字。
So if I enter 6, it should return numbers like 6, 42, 51, 33, 123 etc. 因此,如果我输入6,则应返回数字6、42、51、33、123等。
I'd really appreciate help since I've been dwelling on this for a while now. 自从我花了很长时间以来,我非常感谢您的帮助。

public static double number() {
    Console.WriteLine("Enter your number! ");
    string enter = Console.ReadLine();
    double x = Convert.ToDouble(enter);        
    for (int i = 0; i < 1000; i++ ) {
        double r;
        double sum = 0;
        while (i != 0) {
            r = i % 10;
            i = i / 10;
            sum = sum + r;
        }
        if (sum == x) {
            Console.WriteLine(i + " ");
        }
    }
    return(0);
}

I am aware of the fact that there is a problem with "return(0)", but I'm not completely sure what exactly it is that this should be returning. 我知道“ return(0)”存在问题,但是我不确定该返回什么到底是什么。

You are almost there: the only remaining problem is that you are modifying your loop counter i inside the nested while loop, which changes the workings of the outer loop. 您几乎在那里:唯一剩下的问题是,您正在嵌套的while循环内修改循环计数器i ,这将更改外部循环的工作方式。

You can fix this problem by saving a copy of i in another variable, say, in ii , and modifying it inside the while loop instead: 您可以通过将i的副本保存在另一个变量(例如ii ,然后在while循环内修改它来解决此问题:

double r;
double sum = 0;
int ii = i;
while (ii != 0) {
    r = iCopy % 10;
    ii /= 10;
    sum = sum + r;
}

I'd suggest trying to do something like this: 我建议尝试做这样的事情:

public static IEnumerable<int> number()
{
    Console.WriteLine("Enter your number!");
    string enter = Console.ReadLine();
    int digitSum = int.Parse(enter);
    foreach (var n in Enumerable.Range(0, 1000))
    {
        if (n.ToString().ToCharArray().Sum(c => c - '0') == digitSum)
        {
            yield return n;
        }
    }
}

When I run this and enter 6 then I get this result: 当我运行它并输入6我得到以下结果:

结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM