无法将类型 'decimal' 隐式转换为"int"。存在显式转换(您是否缺少强制转换?



我用C#编码,需要与DecimalDouble值相乘,但标题中一直有错误。

这是我的代码:

private void button1_Click(object sender, EventArgs e)
{
        try
        {
            int caloriesBurned;
            if (radioButtonMale.Checked == true)
            {
                Decimal textBoxInt = Convert.ToDecimal(textBox1.Text);
                Decimal maleusage = 0.44M;
                caloriesBurned = Decimal.Multiply(maleusage, textBoxInt);
            }
        }
        catch (Exception error)
        {
            MessageBox.Show(error.ToString());
            MessageBox.Show("Indtast venligst et tal");
            throw;
        }
    }

编辑:解决了!谢谢大家!新手失误。很抱歉

您可以将变量声明为十进制,如下所示:

decimal caloriesBurned;

您正在尝试将2个十进制变量相乘,然后尝试将值设置为整数值,为了做到这一点,您可以这样做:

caloriesBurned = Convert.ToInt32(Decimal.Multiply(maleusage, textBoxInt));

但这样做会丢失,之后的所有数字,因此将caloriesBurned设置为decimal类型而不是int类型会使代码发挥作用。

您想要将decimal分配给int类型

caloriesBurned = Decimal.Multiply(maleusage, textBoxInt);

将字段类型更改为十进制,因为上面的计算返回decimal。。。

相关内容

最新更新