微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 将数字增加1

我想看到label6显示用户选择号码的正确次数.而label7显示用户选择错误次数.它不会增加一个.

错误1运算符”无法应用于’string’类型的操作数
错误2运算符”无法应用于’string’类型的操作数

private void button1_Click(object sender,EventArgs e)
    {
        string correct="0";
        string incorrect="0";
        RandomNumber(0,99);
        button2.Enabled = true ;
        button1.Enabled = false;
        label3.Visible = true;
        if (textBox1.Text == label1.Text)
            label3.Text=("Winner");
               label6.Text = correct +1;
               if (textBox1.Text != label1.Text)
                   label7.Text = incorrect= +1;
            label3.Text=(string.Format("Sorry - You Lose,The number is {0}",label1.Text));

    }

编辑(从OP回答他自己的问题):

我已经尝试了你的建议方式,但每次我猜错了数字都不会增加一个.

private void button1_Click(object sender,EventArgs e)


    {
        int correct=0;
        int incorrect=0;
        RandomNumber(0,99);
        button2.Enabled = true ;
        button1.Enabled = false;
        label3.Visible = true;
        if (textBox1.Text == label1.Text)
        {
            label3.Text = ("Winner");
            label6.Text = (++correct).ToString(); 
        }

        else if (textBox1.Text != label1.Text)
        {
            label7.Text = (incorrect+1).ToString(); 

            label3.Text = (string.Format("Sorry - You Lose,label1.Text));
        }


    }

解决方法

添加到字符串,正确和不正确只会附加所添加内容的字符串表示.您必须将其转换为整数类型,然后递增,然后转换回字符串.但是,将这些变量保持为整数实例变量会更容易.这种方式递增是微不足道的,实际上你保持正确的计数,而不是每次点击按钮都重置. (代码实际上存在许多问题)

// instance variables
private int correct = 0;
private int incorrect = 0;

private void button1_Click(object sender,EventArgs e)
{
    RandomNumber(0,99);
    button2.Enabled = true ;
    button1.Enabled = false;
    label3.Visible = true;
    if (textBox1.Text == label1.Text)
    {
        label3.Text=("Winner");
        label6.Text = (++correct).ToString(); // convert int to string
    }
    // indentation does not indicate the block
    else //if (textBox1.Text != label1.Text)
    {
        label3.Text=(string.Format("Sorry - You Lose,label1.Text));
        label7.Text = (++incorrect).ToString();
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐