C# 运算符“*”不能应用于“double”和“decimal”类型的操作数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8903632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Operator '*' cannot be applied to operands of type 'double' and 'decimal'
提问by user1152722
I get this message in my program but i don't know how to fix it i have search on the net but don't find any thing that can help me.
我在我的程序中收到这条消息,但我不知道如何解决它我在网上搜索过但没有找到任何可以帮助我的东西。
private double Price;
private int Count;
private double Vat;
private const double foodVATRate = 0.12, otherVATRate = 0.25;
private decimal Finalprice;
private decimal Rate;
public void Readinput()
{
Finalprice = (decimal)(Price * Count);
}
private void cal()
{
char answer = char.Parse(Console.ReadLine());
if ((answer == 'y') || (answer == 'Y'))
Vat = foodVATRate;
else
Vat = otherVATRate;
Rate = Vat * Finalprice;
Operator '*' cannot be applied to operands of type 'double' and 'decimal' is what comes up on Rate = Vat * Finalprice; and i don't know i can fix it
运算符 '*' 不能应用于类型为 'double' 的操作数,而 'decimal' 是 Rate = Vat * Finalprice; 我不知道我能解决它
回答by Andrew Barber
Change foodVATRateto decimal, too. There doesn't seem to be any reason for it to be double.
也foodVATRate改为decimal。似乎没有任何理由使它成为双重。
回答by Mark Brackett
You need to cast one to the other. My guess is that both Price and all of your VAT rates should really be decimal - double isn't (usually) appropriate for dealing with any type of monetary values.
您需要将一个转换为另一个。我的猜测是价格和所有增值税税率都应该是十进制的 - double (通常)不适合处理任何类型的货币价值。
回答by Junichi Ito
Try this:
尝试这个:
Rate = (decimal)Vat * Finalprice;
回答by Ergwun
You can't multiply a decimalby a double. You can fix this by type casting, but you probably just want to stick with using decimalfor all prices and VAT rates throughout.
您不能将 a 乘以decimala double。您可以通过类型转换来解决这个问题,但您可能只想坚持使用decimal所有价格和增值税率。
The type decimalwas designed to be useful for financial calculations since it offers high precision at the cost of reduced range for the size of the type in bytes.
该类型decimal旨在用于财务计算,因为它提供高精度,但以字节为单位减小了类型大小的范围。

