首页 > 解决方案 > 卡住循环/迭代 [升 C]

问题描述

我正在尝试创建一个循环,当我键入“ok”时,它将添加所有输入的数字并显示所有输入数字的总和。如果你能给我一个方法,那就太好了。谢谢你。

class Program
{

    static void Main(string[] args)
    {

        {
            int sum = 0;

            while (true) {

                Console.WriteLine("Please enter a number: \n");
                int num;
                if (int.TryParse(Console.ReadLine(), out num))
                {
                    {
                        if (num == 0)
                        {
                            break;
                            sum += num;
                        }
                    }
                }
                else if (Convert.ToString(num) == "ok")
                {
                    Console.WriteLine("Sum is " + sum);
                    break;
                }
           }
        }

     }


  }

}

标签: c#console

解决方案


这是一个解决方案,请在复制粘贴之前阅读 C# 基础知识。

// Setup our variables
string input;
var total = 0;

// Begin a loop running forever
do
{
    // Get the user input as a string - the code has no idea it is a number at this point
    Console.Write("Input a number: ");
    input = Console.ReadLine();

    // See if we can parse the string into a number, this function returns a boolean, hence if the string is an int, the `total += value` block is executed
    if (int.TryParse(input, out var value))
    {
        total += value;
    }
    else if (input.ToLower() != "ok")
    {
        // If the input string is not an int, and the input is not "ok" then, let them know their input was not a number
        Console.WriteLine("Please input a number...");
    }
    else
    {
        // The input string was not an int, but it was the string "ok", therefore break out of this loop
        break;
    }
} while (true);

// After breaking out of the loop, print the total
Console.WriteLine(total);

推荐阅读