簡體   English   中英

我的代碼有什么問題? 正確打印數字總和以數字 3 和數字 6 結尾的數字存在一些問題

[英]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

我想知道我所謂的致命錯誤在哪里,因為我是使用C#編碼的新手,但在這種情況下,我真的看不出有什么問題。

            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));

您忘記為每個數字更改變量sum = 0

只需更新foreach循環中每個步驟的變量總和。

請查看下一個代碼:

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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM