我不懂我自己的代码

时间:2015-05-31 05:14:05

标签: c#

假设用户想要计算任意数字的乘法表,直到他们想要的任何行。因此用户输入2然后他输入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;
}

2 个答案:

答案 0 :(得分:1)

在检查计数器之前递增,这就是你必须在-1开始计数器的原因。

  if (counter == loops)
  {
       break;
  }     
  counter += 1; //move below the if statement

答案 1 :(得分:0)

我不确定我是否明白你要做什么。这有用吗?

SELECT col1 As Col3, SUM(CASE WHEN col2 = 'Yes' THEN 1 ELSE 0 END) As col4
FROM yourTable
GROUP BY col1