簡體   English   中英

C#While循環(添加用戶輸入以達到目標)

[英]C# While Loop (adding the user input to reach a target)

我需要創建一個程序,添加用戶輸入以達到目標,結果如下所示。

在此處輸入圖片說明

我必須為此使用“ While循環”,但很難使用while循環...

這是我的代碼

Console.WriteLine("Enter Target Value: 6");

int total = 0;
int target = 6;
int i;
for (i = 1; i <= 4; i++)
{
    Console.Write("Enter #{0}:\t", i);
    total += Convert.ToInt32(Console.ReadLine());
}

while (total == target);

Console.WriteLine("It took {0} inputs to take the sum to\t{1}",i, total);
Console.ReadLine();

您能幫我發現問題嗎?

這是完整的示例。

  static void Main(string[] args)
    {


        try
           {
            int i = 0;
            int number;
            int input=0;
            Console.WriteLine("Enter target number ");

            number =   int.Parse(Console.ReadLine());
            while (input != number && input < number)
            {
                Console.WriteLine($"Enter number  {i+1}");
                input += int.Parse(Console.ReadLine());
                i++;


            }
            Console.WriteLine($"It took {i} number to make the sum {number}");


          }
          catch (Exception e)
          {



          }


        Console.ReadLine();
    }

您知道用戶將輸入什么號碼嗎? 不,你不知道。 因此,您不知道要達到總和還需要多少個數字。

選擇適合該工作的工具。

對於循環

“ For”循環用於將特定代碼塊重復已知次數。

While循環

“ While”循環用於未知次數重復特定代碼塊,

給定以上兩個選項,您應該選擇一個while循環,因為您不知道需要多少次才能要求用戶輸入數字來達到總和。 可能是1次或多次。

在C#中,還有一個do while循環,如果您知道必須至少執行一次甚至可能多次執行某事,則可以使用do while循環,因此,對於您而言,最好的選擇是使用do while

您可以閱讀更多有關while循環for循環while的內容

您的代碼是完全可操作的。 我希望這有幫助:

Console.WriteLine("Enter Target Value: 6");

int total = 0;
int target = 6;
int i = 1;

while (i <= 4)
{
    Console.Write("Enter #{0}:\t", i);
    total += Convert.ToInt32(Console.ReadLine());
    i++;
}

while (total == target);
Console.WriteLine("It took {0} inputs to take the sum to\t{1}",i, total);

Console.ReadLine();

暫無
暫無

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

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