2014-09-27 35 views
1

好吧,我有这样的代码:奇怪的错误“操作符‘*’不能应用于类型‘双’和‘小数’的操作数”

decimal jewels = numericUpDown1.Value; 
int price = 0.35/100 * jewels; 
MessageBox.Show(price.ToString()); 

但出于某种奇怪的原因,我得到这个错误:`

operator '*' cannot be applied to operands of type 'double' and 'decimal'`.

我试过使用所有不同的类型,如float,double和int,它们都不起作用!

任何想法?

+2

您不能乘以一个“小数”和“双”二rectly。 ('0.35/100'是'双')。先将'double'转换为'decimal',反之亦然。 – 2014-09-27 10:46:36

+0

通过使它们都是相同的类型来简化它 - 然后再回到int。 int i = Convert.ToInt32(0.35m * 100m) – kidshaw 2014-09-27 11:13:09

回答

1

您无法将decimal值与double的值相乘。如果您使用decimal文字值,乘法正常工作:

0.35M/100M * jewels 

将其分配到一个int变量,你必须将结果转换为int

int price = (int)(0.35M/100M * jewels); 

你可能想圆的decimal值首先,因为只是施放它会截断该值:

int price = (int)Math.Round(0.35M/100M * jewels); 
+0

我建议传入Round上的MidpointRounding参数。 MidpointRounding.AwayFromZero很可能会按照您的打算。请参阅http://msdn.microsoft.com/en-us/library/system.midpointrounding(v=vs.110).aspx – Trevor 2014-09-27 12:45:20

+0

@Trevor:由于四舍五入的价格是一个价格,所以四舍五入的四舍五入似乎更合适。这是'Round'方法的默认值。 – Guffa 2014-09-27 13:28:38

+0

为什么downvote?如果你不解释你认为什么是错的,它不能改善答案。 – Guffa 2014-09-27 13:29:04

0

您需要专门从decal转换为其他数字格式,如double。因此,尝试:

int price = 0.35/100 * Convert.ToDouble(jewels); 

或者:

int price = 0.35/100 * (double)jewels; 
1

这将工作,

decimal price = Convert.ToDecimal(0.35/100) * jewels; 

,如果你想价格为int:

int price = Convert.ToInt32(Convert.ToDecimal(0.35/100) * jewels); 

和..我认为宝石不需要是小数,因为它的价值是科曼克从数字上下控制,将永远是int?

相关问题