簡體   English   中英

我只需要輸出在此控制台應用程序中打印的最后一個 int。 我正在使用 foreach 循環。 C# 控制台應用程序

[英]I need to output only the last int that is printed out in this console app. I'm using a foreach loop. C# console app

我正在嘗試對字符串中每個字符的 ASCII 值求和。 打印出來的最后一個數字是我唯一想要顯示的數字。 因此,如果我輸入“chris”,我將返回 99、203、317、422 和 537。537 是我想要顯示的正確值,如何僅打印出 537?

using System;

namespace BLConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            bool executeLoop = true;
            while (executeLoop)
            {
                Console.WriteLine("Please enter a word for the sum of it's ASCII value !!!");
                Console.WriteLine("Type the word 'exit' at any time to escape ...");
                string word = Console.ReadLine();

                if (word != "EXIT" || word != "Exit" || word != "exit")
                {
                    int  sum = 0;
                    foreach (char c in word)
                    {
                        sum += c;
                        Console.WriteLine((int)sum);
                    }
                }

                if (word == "EXIT" || word == "Exit" || word == "exit")
                  {
                    executeLoop = false;
                    return;
                }
            }
        }
    }
}

您可以簡單地將WriteLine放在循環之后,因此它只寫入最終和。 此外,您可以只使用true作為循環的條件,因為return會立即跳出循環。 此外,您可以使用string.Equals方法進行不區分大小寫的比較:

while (true)
{
    Console.WriteLine("Please enter a word for the sum of it's ASCII value !!!");
    Console.WriteLine("Type the word 'exit' at any time to escape ...");

    string word = Console.ReadLine();

    if (word.Equals("exit", StringComparison.OrdinalIgnoreCase))
    {
        return;
    }

    int sum = 0;

    foreach (char c in word)
    {
        sum += c;
    }

    Console.WriteLine(sum);
}

暫無
暫無

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

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