我不懂我自己的代码
本文关键字:代码 自己的 懂我 不懂 | 更新日期: 2023-09-27 17:51:18
假设用户想要计算任何数字的乘法表,直到他们想要的任何一行。所以用户输入2,然后他输入10。控制台会写出所有以10为倍数的内容。我的代码这样做,但我不明白为什么我必须设置我的int counter = -1
,而不是0
。
try
{
Console.WriteLine("The number of lines you want to calculate up to ");
int loops = Convert.ToInt16(Console.ReadLine());
if (loops <0)
{
Console.WriteLine("Can not enter a value less then zero... Try Again?");
Console.ReadLine();
goto Start;
}
Console.WriteLine("What multiplication tables would you like to do ?");
int m = Convert.ToInt16(Console.ReadLine());
for (int counter = -1; counter <= loops; counter+=1)
{
for (int mt = m; mt >= 0; mt += m)
{
if (mt % m == 0)
{
counter += 1;
if (counter == loops)
{
break;
}
}
Console.WriteLine(mt);
}
}
Console.ReadLine();
}
catch
{
Console.WriteLine("Enter numbers only");
Console.ReadLine();
goto Start;
}
在检查计数器之前进行递增,这就是为什么必须从-1开始计数。
if (counter == loops)
{
break;
}
counter += 1; //move below the if statement
我不确定我是否明白你想做什么。这能起作用吗?
try
{
Console.WriteLine("The number of lines you want to calculate up to");
int loops = Convert.ToInt16(Console.ReadLine());
if (loops < 0)
{
Console.WriteLine("Can not enter a value less then zero... Try Again?");
Console.ReadLine();
goto Start;
}
Console.WriteLine("What multiplication tables would you like to do ?");
int m = Convert.ToInt16(Console.ReadLine());
for (int i = 1; i <= loops; i++)
{
Console.WriteLine(i * m);
}
}
catch
{
Console.WriteLine("Enter numbers only");
Console.ReadLine();
goto Start;
}