简体   繁体   中英

What is wrong with my code? There is some problem with printing correctly the numbers which sum of the digits end with the number 3 and the number 6

I want to know where is my so called fatal error because I am kinda newbie in coding with C# but in this case i really can not see anything wrong.

            List<int> numbers = Console.ReadLine().Split(',').Select(int.Parse).ToList();
        List<int> even = new List<int>();
        List<int> odd = new List<int>();
        List<int> sum3 = new List<int>();
        List<int> sum6 = new List<int>();
        int sum = 0;
        foreach(var nums in numbers)
        {
            if(nums%2==0 && nums % 10 == 4 || nums % 10 == 2)
            {
                even.Add(nums);
            }
            else if(nums % 2 != 0 && nums % 10 == 5 || nums % 10 == 7)
            {
                odd.Add(nums);
            }
            int n = nums;
            while (n != 0)
            {
                sum += n % 10;
                n = n / 10;
            }
            if (sum % 10 == 3)
            {
                sum3.Add(nums);
            }
            else if (sum % 10 == 6)
            {
                sum6.Add(nums);
            }
        }
        Console.WriteLine(String.Join(',',even));
        Console.WriteLine(String.Join(',', odd));
        Console.WriteLine(String.Join(',', sum3));
        Console.WriteLine(String.Join(',', sum6));

You forget to change variable sum = 0 for each number.

Just update variable sum for each step inside your foreach cycle.

Please review next code:

int sum = 0;
foreach(var nums in numbers)
{
    if(nums%2==0 && nums % 10 == 4 || nums % 10 == 2)
    {
        even.Add(nums);
    }
    else if(nums % 2 != 0 && nums % 10 == 5 || nums % 10 == 7)
    {
        odd.Add(nums);
    }
    
    sum = 0; // There is your issue (you forget about it)
    int n = nums;
    while (n != 0)
    {
        sum += n % 10;
        n = n / 10;
    }
    if (sum % 10 == 3)
    {
        sum3.Add(nums);
    }
    else if (sum % 10 == 6)
    {
        sum6.Add(nums);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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