即使没有错误,程序也无法正常工作

时间:2018-02-02 13:26:11

标签: c# visual-studio

 private void button1_Click(object sender, EventArgs e)
    {
        {
            int a = 127;
            int v = Roll(a);
            MessageBox.Show(String.Format("Roll for (0) is (1), ", a, v));
        }
        int Roll (int x)
        {
            return (x <= 2) ? x : x + Roll(x / 2);
        }
    }

我已经尝试了很多东西,但这是我能得到的最好的东西,但仍然无法正常工作

1 个答案:

答案 0 :(得分:2)

你的语法都错了。请参阅下面评论中的注释。

private void button1_Click(object sender, EventArgs e)
{
    int a = 127;
    int v = Roll(a);

    // Use curly braces, not parens for String.Format
    MessageBox.Show(String.Format("Roll for {0} is {1}, ", a, v));

    // If you're using C# 6+, you could also use string interpolation
    MessageBox.Show($"Roll for {a} is {v}");
}

// Roll should be it's own method, outside of your click handler
private int Roll (int x)
{
    return (x <= 2) ? x : x + Roll(x / 2);
}

// Again, if you're using C# 6+, you could simplify your Roll method
// using expression bodied members
private int Roll (int x) => (x <= 2) ? x : x + Roll(x / 2);

其他信息