我可以使用For循环来提供不同的结果/值吗?

时间:2011-10-07 10:01:14

标签: c#

示例代码(错误但是参考):

for (int i = 0; i < 10; i++)
{
    if ((i % 3) == 0 )
    {
         Console.WriteLine(i+":x");
    }
    else if ((i % 2) == 0 
    {
         Console.WriteLine(i+":y");
    }
    else 
    {
         Console.WriteLine(i+":z");
    }
}

我想要的结果:

1:x
2:y
3:z
4:x
5:y
6:z
7:x
8:y
9:z
10:x

4 个答案:

答案 0 :(得分:3)

switch (i%3)
{
case 0: // :z
case 1: // :x
case 2: // :y
}

答案 1 :(得分:2)

你想......

for (int i = 1; i <= 10; i++)
{
        if ((i % 3) == 1)
        {
         Console.WriteLine(i+":x");
        }
        else if ((i % 3) == 2)
        {
         Console.WriteLine(i+":y");
        }
        else //if ((i % 3) == 0)
        {
         Console.WriteLine(i+":z");
        }
}

或更简单......

for (int i = 0; i < 10; i++)
{
    switch (i%3)
    {
    case 0:
      Console.WriteLine(i+":z");
      break;
    case 1:
      Console.WriteLine(i+":x");
      break;
    case 2:
      Console.WriteLine(i+":y");
      break;
    }
}

答案 2 :(得分:2)

这里重要的部分是不要改变你计算模数的数字。

换句话说,不是检查i % 3 == 0然后检查i % 2 == 0,而是检查:

  • i % 3 == 0 - &gt; X
  • i % 3 == 1 - &gt; ÿ
  • i % 3 == 2 - &gt; ž

有很多方法可以做你想做的事:

提示:要测试其中任何一项,您可以使用LINQPad,只需复制并粘贴上述代码示例之一,点击F5即可运行,您将看到输出符合您的要求。

使用数组:

void Main()
{
    string[] letters = new[] { "x", "y", "z" };
    for (int index = 0; index < 10; index++)
    {
        Console.WriteLine((index + 1) + ":" + letters[index % 3]);
    }
}

带开关/外壳

void Main()
{
    for (int index = 0; index < 10; index++)
    {
        switch (index % 3)
        {
            case 0:
                Console.WriteLine((index + 1) + ":x");
                break;
            case 1:
                Console.WriteLine((index + 1) + ":y");
                break;
            case 2:
                Console.WriteLine((index + 1) + ":z");
                break;
        }
    }
}

使用if-statements

void Main()
{
    for (int index = 0; index < 10; index++)
    {
        if (index % 3 == 0)
            Console.WriteLine((index + 1) + ":x");
        else if (index % 3 == 1)
            Console.WriteLine((index + 1) + ":y");
        else
            Console.WriteLine((index + 1) + ":z");
    }
}

答案 3 :(得分:0)

    var d = new Dictionary<int,string> { {1,"x"}, {2,"y"}, {0,"z"} };
    for(int i = 1; i<= 10; i++)
        Console.WriteLine("{0}:{1}", i, d[i%3]);