简体   繁体   English

用户进入后while不会结束

[英]While will not end after user enters

Everything runs fine.一切运行良好。 However, I need the loop to end contingent upon how many numbers the user enters in the first question.但是,我需要根据用户在第一个问题中输入的数字来结束循环。

using System;

namespace Looping
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("How many numbers will you provide?");
            int numbersProvide = Convert.ToInt32(Console.ReadLine());

            int i = 0;

            while (i <= numbersProvide)

            {
                Console.WriteLine("Please enter number:");
                int firstNum = Convert.ToInt32(Console.ReadLine());

                int j;
                int sum = 0;
              
                double addDiv;

                for (j = 1; j <= 25; j++)
                {
                    
                    if (firstNum % j == 0)
                    {
                       addDiv = firstNum / j;
                       Console.WriteLine(firstNum + " is divisible by " + j + "(" + addDiv + ")");
                        sum += j;

                    }
                }
                Console.WriteLine("The sum of the quotient is: " + sum);

            }
            Console.ReadKey();
        }
    }
}

You set int i = 0;你设置int i = 0; and i never increases. i永远不会增加。 Nor does numbersProvide decrease.数字也不会numbersProvide

Since you have a fixed amount of times that the loopo shall run, a for loop is much more suitable for the situation than the while loop you have.由于循环运行的次数是固定的,因此for循环比while循环更适合这种情况。 Use while loops if you don't know how often the loop will run.如果您不知道循环运行的频率,请使用while循环。 Use for loops, if you know the number of runs in advance.如果您事先知道运行次数,请使用for循环。

A typical for loop will combine your declaration ( int i=0 ), the condition ( i <= numbersProvide ) and the missing increment ( i++ ) in one line.典型的 for 循环会将您的声明( int i=0 )、条件( i <= numbersProvide )和缺失的增量( i++ )组合在一行中。

for (int i=0; i<=numbersProvide; i++)

When seeing that, I immediately recognize that the loop is off by one and it should be当看到这一点时,我立即意识到循环关闭了一个,它应该是

for (int i=0; i<numbersProvide; i++)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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