0

我想打印 53 到 96 之间的 7 的倍数

代码:

int tbl = 0;
while(!(tbl > 53) || !(tbl < 96))
{
   tbl = tbl + 7;
   while(tbl > 53 && tbl < 96)
   {
      Console.WriteLine(tbl);
      tbl = tbl + 7;
   }
}
Console.ReadLine();

输出:

输出

输出应该是: 56, 63, 70, 77, 84, 91 它应该在 91 处停止,但不是在 91 处停止

4

4 回答 4

4

非常基本的方法

int tbl=53;
while  (tbl < 96)
{
   if (tbl % 7 == 0)
      Console.WriteLine(tbl);

   tbl++;
}
于 2018-12-13T06:02:42.593 回答
3

这是做到这一点的最好和最快的方法,当你碰到一个能被 7 整除的数字时,你继续增加 7 而不是 1

int tbl = 53;

while  (tbl < 96)
{
   if (tbl % 7 == 0){
      Console.WriteLine(tbl);
      tbl+=7;
      continue;
   }
   tbl++;
}
于 2018-12-13T06:06:57.063 回答
0

由于我们想打印出 7一项,for循环似乎是最简单的选择

int start = 53;
int stop = 96;

for (int tbl = (start / 7 + (start % 7 == 0 ? 0 : 1)) * 7; tbl < stop; tbl += 7)
   Console.WriteLine(tbl);

Console.ReadLine();

如果53值是固定的,我们可以预先计算起始值(53 / 7 + (53 % 7 == 0 ? 0 : 1)) * 7 == (7 + 1) * 7 == 56::

for (int tbl = 56; tbl < 96; tbl += 7) 
  Console.WriteLine(tbl); 

Console.ReadLine();
于 2018-12-13T06:37:35.717 回答
-1

它需要&&在第一个 while 循环中,而不是||

于 2018-12-13T06:03:03.227 回答