运算符“*"不能应用于“string"和“int"类型的操作数 [英] Operator '*' cannot be applied to operands of type 'string' and 'int'

查看:61
本文介绍了运算符“*"不能应用于“string"和“int"类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

namespace exer4
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnTotal_Click(object sender, EventArgs e)
        {
            int overtime = Convert.ToInt32(txtHours.Text) - 30;
            int salary = Convert.ToInt32(txtHours.Text)*250;
            double tax = (salary + overtime) * .10;
            int deduction = salary - (300 + 400);

            //operator '>' cannot be applied to operands of type 'string' and 'int'
            if Convert.ToInt32(txtHours.Text > 30)
            {
                lblName.Text = txtName.Text;
                lblSalary.Text = Convert.ToString(overtime *120) + (salary - (deduction - tax)); 


            }
            else
            { 
                // //operator '*' cannot be applied to operands of type 'string' and 'int'
                lblSalary.Text = Convert.ToString(txtHours.Text) * 250;
            }
       }
  }

推荐答案

你的 if 语句应该是

Your if statement should be

if (Convert.ToInt32(txtHours.Text) > 30)

另一行应该是

lblSalary.Text = Convert.ToString(Convert.ToInt32(txtHours.Text) * 250);

或者更好的是将 txtHours 文本转换为 int 并将其保存在一个变量中以供重用.

Or better yet convert the txtHours text to an int and keep it in a variable to be reused.

    private void btnTotal_Click(object sender, EventArgs e)
    {
        int hours = Convert.ToInt32(txtHours.Text);
        int overtime = hours - 30;
        int salary = hours * 250
        double tax = (salary + overtime) * .10;
        int deduction = salary - (300 + 400);

        if(hours > 30)
        {
            lblName.Text = txtName.Text;
            lblSalary.Text = ((overtime *120) + (salary - (deduction - tax))).ToString(); 
        }
        else
        { 
            lblSalary.Text = salary.ToString();
        }
   }

这篇关于运算符“*"不能应用于“string"和“int"类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆