use*_*480 0 c# type-conversion
我写了这段代码我在if(tot = 100)时得到错误double类型的Literal不能隐式转换为十进制
//value in textboxes
decimal p1 = Convert.ToDecimal(TextBox2.Text);
decimal p2 = Convert.ToDecimal(TextBox3.Text);
decimal p3 = Convert.ToDecimal(TextBox4.Text);
decimal p4 = Convert.ToDecimal(TextBox5.Text);
decimal p5 = Convert.ToDecimal(TextBox6.Text);
decimal p6 = Convert.ToDecimal(TextBox7.Text);
//adding all the p's
decimal tot = p1 + p2 + p3 + p4 + p5 + p6;
if (tot = 100.00)
{
Label2.Text = "Percentage is 100"
}
else
{
Label2.Text = "Total of percentages is not 100.";
}
Run Code Online (Sandbox Code Playgroud)
要指定decimal带小数点的文字,必须使用小数点说明符M:
if(tot == 100.00M)
Run Code Online (Sandbox Code Playgroud)
否则,编译器假定您需要a double(异常消息所指的是 - 如果没有显式转换,则double不能转换为小数).
但是,在此示例中,这.00是多余的,因此您可以使用:
if(tot == 100M)
Run Code Online (Sandbox Code Playgroud)
如其他答案中所述,您必须确保==在比较if语句中的值时使用.如果你这样做了,你会得到一个稍微不同的例外:"Operator '==' cannot be applied to operands of type 'decimal' and 'double'"这可能会让事情变得更加清晰.