[英]C# Operator '*' cannot be applied to operands of type 'double' and 'decimal'
A couple errors I am struggling to understand. 我正在努力理解一些错误。 I am attempting to make a sales tax calculator.
我正在尝试制作营业税计算器。 But keep getting operation error because I cannot multiply a decimal by decimal.
但是由于我无法将十进制乘以十进制,所以会不断出现操作错误。 Here is my code for my calulate button:
这是我的计算按钮的代码:
decimal decTax;
decimal decTotal;
string input;
decimal decOrder;
// Accept the order from the Console window
Console.Write("Enter order in dollars: $");
input = Console.ReadLine();
Decimal.TryParse(input, out decOrder);
// Calculate the sales tax
decTax = (0.06D * (decOrder + decTax));
decTotal = (decOrder + decTax);
// Write the results to the Console Window
Console.WriteLine();
Console.WriteLine("The Total is " & decTotal.ToString("c"));
Console.ReadLine();
The error is exactly what it says. 该错误正是它所说的。 You can't multiply a decimal by your literal double 0.06D.
您不能将十进制数乘以文字双精度数0.06D。 The reason why you can't do that implicitly is because converting a
decimal
to a double
can result in a lose of precision. 之所以不能隐式执行此操作,是因为将
decimal
转换为double
精度会导致精度下降。 The compiler won't make an automatic conversion if there is a possibility of losing precision. 如果有可能失去精度,编译器将不会进行自动转换。
Try casting it to a decimal too: 也尝试将其转换为小数:
decTax = ((decimal)0.06 * (decOrder + decTax));
Or you can use the m
suffix to indicate that your literal is a decimal and not a double: 或者,您可以使用
m
后缀表示您的文字是十进制而不是双精度:
decTax = 0.06m * (decOrder + decTax));
Note, however, in the code you posted in your question you never assigned an initial value to decTax
. 但是请注意,在问题中发布的代码中,您从未为
decTax
分配初始值。 So decOrder + decTax
can't be calculated. 因此无法计算
decOrder + decTax
。 It's unclear from your question what you intended decTax
to be in that case, but it needs an initial value. 从您的问题尚不清楚在这种情况下您打算将
decTax
设置为什么,但是它需要一个初始值。
D
means Double
for Decimal
use M
. D
表示Decimal
使用M
Double
。
decTax = (0.06M * (decOrder + decTax));
Refer to this documentation for more information. 有关更多信息,请参考此文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.