简体   繁体   中英

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

I need to create a program that adding the user input to reach a target, as a result, is just like below.

在此处输入图片说明

I have to use 'While Loop' for this, but it is difficult for me to use while loop...

Here is my code

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

Could you please help me to find the problems?

Here is the complete example.

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

Do you know what number the user will enter? No, you do not know. So you do not know how many numbers will it take to reach the sum as well.

Pick the right tool for the job.

For Loop

A "For" Loop is used to repeat a specific block of code a known number of times.

While Loop

A "While" Loop is used to repeat a specific block of code an unknown number of times,

Given the above 2 options, your pick should be a while loop since you do NOT know how many times you will need to ask the user to enter a number to reach the sum. It may be 1 or many, many times.

In C#, there is also the do while loop, which is to be used if you know you must do something at least once and possibly more, Therefore, for your case the best option would be to use do while .

You may read more on while loop , for loop , and do while .

Your code is perfectly operational. I hope this helps:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM