我正在研究 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++;
}
}
}
最佳答案
您的方法(以及迄今为止的其他答案)正在测试 a
和 b
之间的每个数字,这非常好。
我在下面尝试的是通过简单的计算找到第一个因子 >= 到 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 循环中的测试较少
- 使用加法 (+) 而不是模数 (%)
关于c# - 在c#中使用while循环,在两个num之间进行计数,仅打印可被第三个num整除的num,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34554406/