我只需要输出在此控制台应用程序中打印出的最后一个 int。我正在使用 foreach 循环。C# 控制台应用



我正在尝试对字符串中每个字符的 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);
}

相关内容

最新更新