c# - 在c#中使用while循环,在两个num之间进行计数,仅打印可被第三个num整除的num

标签 c# while-loop

我正在研究 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 添加到这个数字,直到我们超过上限绑定(bind),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/

相关文章:

c# - 在 asp.net-mvc 中创建可重用部分的最佳方法

c# - JavaScript 和 Windows 窗体之间的交互

似乎无法让我的 While 语句发挥作用

c++ - 为什么这会进入无限循环?

c# - 有什么方法可以在 .net 中为 iphone 开发应用程序

c# - 来自模型的不同值

C#批处理文件执行永不退出

c - 在我可以在循环中使用的相同变量名中 malloc 一些其他内存量之前,我需要采取哪些步骤?

c# 将 mysql 当前结果与下一个结果进行比较

python - 请对我的示例 Python 程序进行代码审查