gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:31:33 27 4
gpt4 key购买 nike

我正在研究 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 之间的每个数字,这非常好。

我在下面尝试的是通过简单的计算找到第一个因子 >= to 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com