我正在研究while循环。我目前正在研究一个问题,要求从名为a,b和c的用户那里获取三个数字。我尝试显示a和b之间的所有数字,这些数字除以c。我玩弄了使用“ if”的想法,但是没有运气。

    public static void Main (string[] args)
    {
        Console.WriteLine ("enter 3 num");
        int num1 = Convert.ToInt32 (Console.ReadLine ());
        int num2 = Convert.ToInt32 (Console.ReadLine ());
        int num3 = Convert.ToInt32 (Console.ReadLine ());
        if (num1 > num2) {
            while (num2 % num3 == 0) {
                Console.WriteLine (num2);
                num2++;
            }
        } else {
            while (num1 % num3 == 0) {
                Console.WriteLine (num1);
                num1++;
            }
        }



    }

最佳答案

您的方法(以及到目前为止的其他答案)正在测试ab之间的每个数字,这非常好。

我在下面尝试的操作是通过简单的计算找到第一个因子> =到a,然后继续将c添加到该数字,直到我们超过上限b

public static void Main (string[] args)
{
    // Note: This crashes if non numeric characters are entered!
    Console.WriteLine ("Please enter 3 numbers:");
    int num1 = Convert.ToInt32(Console.ReadLine());
    int num2 = Convert.ToInt32(Console.ReadLine());
    int divisor = Convert.ToInt32(Console.ReadLine());

    // Find the lowest and highest in case they are entered in the wrong order
    int lowerNum = Math.Min(num1, num2);
    int upperNum = Math.Max(num1, num2);

    // Find the first factor over the lower bound
    // E.g. for a = 10, b = 20, c = 3, we have remainder = 1
    //      = 10 + (3 - 1)
    //      = 12
    int remainder = lowerNum % divisor;
    int factor = (remainder == 0)
      ? lowerNum
      : lowerNum + (divisor - remainder);

    // Calculate all other factors up to the upper bound by simple addition
    while(factor <= upperNum){
      Console.WriteLine(factor);

      factor += divisor;
    }

}


这种方法的优点:


for循环中的测试较少
使用加法(+)而不是取模(%)


.NET Fiddle here

关于c# - 在C#中使用while循环,计数两个num之间仅打印可被第三个num整除的num,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34554406/

10-10 16:28