加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将数字增加1

发布时间:2020-12-15 20:02:09 所属栏目:百科 来源:网络整理
导读:我想看到label6显示用户选择号码的正确次数.而label7显示用户选择错误的次数.它不会增加一个. 错误1运算符”无法应用于’string’类型的操作数 错误2运算符”无法应用于’string’类型的操作数 private void button1_Click(object sender,EventArgs e) { str
我想看到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();
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读