我可以'我不想在C#中以我想要的方式输出数字



我想输入一个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);
}

您可以使用具有预定义值的for循环来执行此操作。

for (int x = Convert.ToInt32(number); x < 102; x++)
{
Console.WriteLine(x);
}
if (x > 0 || x < 101)

几乎每一个数字都是如此。您想将||更改为&amp;

Console.Write(x++);

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

while (x != 102);

这只检查一个值。例如,如果你输入103,你会得到一个无穷大循环。尝试<102

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

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

我认为最好使用"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);
}
}

或者,如果你想使用"dowhile"循环,可以这样修改你的代码:

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
}

如果用户试图给出非数字的输入,此代码也会进行处理。

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);
}

最新更新