C# do while 循环使用 if 语句打印奇数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15963121/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 18:37:04  来源:igfitidea点击:

do while loop using an if statement to print odd numbers

c#loopsif-statementwhile-loopdo-while

提问by coderInTheMaking

At the moment I am learning loops. I am trying to create a console application which uses a do while loop to print all odd integers between 20 and 0.

目前我正在学习循环。我正在尝试创建一个控制台应用程序,它使用 do while 循环来打印 20 和 0 之间的所有奇数。

Why when I uncomment ifstatement below my code does not print anything and never finishes?

为什么当我取消注释if我的代码下面的语句时不会打印任何内容并且永远不会完成?

using System;

class Program
{
  static void Main(string[] args)
  {
     int i = 20;
     do 
     {
        // if (i%2 !=0)
        {
           Console.WriteLine(
              "When counting down from 20 the odd values are: {0}", i--);
        }
      } while (i >=0);
   }
}

回答by p.s.w.g

I think the main issue you're having is that the decrement (i--) only occurs inside the if block. That means when the condition fails, you will enter an infite loop. You can move the decrement outside the if block to fix that. Try this:

我认为您遇到的主要问题是减量 ( i--) 仅发生在 if 块内。这意味着当条件失败时,您将进入一个无限循环。您可以将减量移到 if 块之外以解决该问题。尝试这个:

Console.Write("When counting down from 20 the odd values are: ");
do 
{
    if (i % 2 != 0)
    {
        Console.Write(" {0}", i);
    }

    i--;
} while (i >= 0);

I also moved the first Console.Writeoutside the loop to reduce redundancy in the output. This will produce:

我还将第一个移到Console.Write循环外以减少输出中的冗余。这将产生:

When counting down from 20 the odd values are: 19 17 15 13 11 9 7 5 3 1

当从 20 倒数时,奇数为:19 17 15 13 11 9 7 5 3 1

回答by Ethan Li

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Do_while_Test
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 20;
            Console.WriteLine();
            Console.WriteLine("A do while loop printing odd values from 20 - 0 ");
         do 
         {
            if (i-- %2 !=0)
            {
             Console.WriteLine("When counting down from 20 the odd values are: {0}", i--);
            }

         } while (i >=0);
         Console.ReadLine();  
        }

    }
}

回答by devilfish17

A for loop may be easier to follow:

for 循环可能更容易遵循:

Console.WriteLine("When counting down from 20 the odd values are: ");
for( int i = 20; i >= 0; i--)
{
    if (i%2 !=0)
    {
       Console.Write(" " + i);
    } 
}

回答by BBL Admin

Sorry, I know this is really old and the initial question was for a DO not a FOR, but I wanted to add what I did to accomplish this outcome. When I Googled the question initially, this is what was returned first despite my query being for a FOR loop. Hopefully someone down the road will find this helpful.

抱歉,我知道这真的很旧,最初的问题是针对 DO 而不是 FOR,但我想添加我为实现这一结果所做的工作。当我最初用 Google 搜索这个问题时,尽管我的查询是 FOR 循环,但这是首先返回的内容。希望有人在路上会发现这很有帮助。

The below will print the odd number index of an array - in this case, Console App args.

下面将打印数组的奇数索引 - 在这种情况下,控制台应用程序参数。

using System;
namespace OddCounterTest
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine(i);
                i++;
            }
        }
    }
}

Output with 6 arguments will be: 1 3 5

带有 6 个参数的输出将是:1 3 5

Moving i++ to the first step in the for loop will get you the even numbers.

将 i++ 移至 for 循环的第一步将使您获得偶数。

using System;
namespace EvenCounterTest
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < args.Length; i++)
            {
                i++;
                Console.WriteLine(i);
            }
        }
    }
}

Output will be: 2 3 4

输出将为:2 3 4

This is setup so you can get the also actual values of the args too rather than simply the count and print of the args index. Just create a string and set the string to args[i]:

这是设置,因此您也可以获得 args 的实际值,而不仅仅是 args 索引的计数和打印。只需创建一个字符串并将该字符串设置为 args[i]:

string s = args[i];
Console.WriteLine(s);

If you need to count and exclude "0" in the event your are printing numbers like the question initially asks, then setup your for loop like so:

如果您在打印数字时需要计算并排除“0”,就像问题最初提出的那样,请像这样设置 for 循环:

for (int i = 1; i <= args.Length; i++);

Notice how "i" is initially set to 1 in this example and i is less than or equal to the array length rather than simply less than. Be mindful of your less than and less than/equal to's or you will get OutOfRangeExceptions.

请注意,在此示例中,“i”最初如何设置为 1,并且 i 小于或等于数组长度,而不是简单地小于。注意你的小于和小于/等于,否则你会得到 OutOfRangeExceptions。