我无法在C#中以我想要的方式输出数字

时间:2019-11-04 13:12:51

标签: c# loops numbers console-application

我想输入1-100之间的数字,控制台应该将输入数字中的所有数字都写到101。如果我输入1-100之间的数字,则程序应该关闭。输入0或101时,我无法关闭程序。如果输入0,则冻结或包含0,如果输入101,则仅写入101。输出数字时,它们之间没有空格。

static void Main(string[] args)
{
    Console.WriteLine("Input a number between 1-100");
    Console.Write("");
    string number = Console.ReadLine();
    int x = Convert.ToInt32(number);
    do
    {
        if (x > 0 || x < 101) //I tried switching out || for &&
        {
            Console.Write(x++);
        }
    } while (x != 102);
}

5 个答案:

答案 0 :(得分:0)

您可以使用带有预定义值的for循环来完成此操作。

for (int x = Convert.ToInt32(number); x < 102; x++)
{
    Console.WriteLine(x);
}

答案 1 :(得分:0)

一种方法是将x的当前值用作循环条件

Console.WriteLine("Input a number between 1-100");
int x = Convert.ToInt32(Console.ReadLine());
while (x > 0 && x < 101)
{
    Console.WriteLine(x++);
}

答案 2 :(得分:0)

if (x > 0 || x < 101)

几乎每个数字都是如此。您要更改||到&&

Console.Write(x++);

将此更改为WriteLine或在x ++的末尾添加一个额外的空间以在它们之间获得空间。

while (x != 102);

这仅检查单个值。如果您输入例如103,则会出现无限循环。尝试<102

答案 3 :(得分:0)

如果用户尝试提供非数字的输入,此代码也会处理。

  int x;
  // read input until user inputs a digit instead of string or etc.
  do
  {
    Console.WriteLine("Input a number between 1-100");
  }
  while (!Int32.TryParse(Console.ReadLine(), out x));

  // exit from program if x isn't between 1 and 100
  if (x < 1 || x > 100)
    return;    

  // else count from given number to 101
  for(int i = x; i < 101; ++i)
  {
    Console.WriteLine(i);
  }

答案 4 :(得分:0)

我认为最好使用“ for”循环:

Console.WriteLine("Input a number between 1-100");
Console.Write("");
string number = Console.ReadLine();
int x = Convert.ToInt32(number);
if( x > 0 && x < 101 )
{
   for( int i = x; i <=101; i++ )
    {
        Console.Write(i);
    }
}

或者,如果您想使用“ do-while”循环,请按以下方式更改代码:

static void Main( string[ ] args )
{
    Console.WriteLine("Input a number between 1-100");
    Console.Write("");
    string number = Console.ReadLine();
    int x = Convert.ToInt32(number);
    do
    {
        if (x > 0 && x <= 101) 
        {
            Console.WriteLine(x++);
        }
        else
        {
            Environment.Exit( 0 ); // when insert 0 or 101
        }
    } while (x < 102);
    Console.ReadKey( ); // when write all numbers, wait for a key to close program
}