[英]discount calculation in c# error on assigning value
有人可以告诉我我的代码有什么问题吗?
我已经尝试过先转换值,但得到的结果相同。
/// <summary>
/// Discount function
/// </summary>
/// <param name="ToDiscount">Price of an item</param>
/// <param name="Discount">Discount</param>
/// <param name="Type">Percent or Amount</param>
/// <returns></returns>
private decimal Discount(decimal ToDiscount, int Discount, DiscountType Type)
{
decimal temp = 0;
try
{
if (Type == DiscountType.Percent)
{
int d = Convert.ToInt32((Discount / 100) * ToDiscount);
decimal f = ToDiscount - d;
temp = f;
}
else if (Type == DiscountType.Currency)
{
decimal FinalDiscount = ToDiscount - Discount;
temp = FinalDiscount;
}
}
catch (Exception ex)
{
Functions.ShowError(ex);
}
return temp;
}
例:
Discount(5000, 5, DiscountType.Percent);
//calculation: (5/100) * 5000 = 250
//discount: 5000 - 250 = 4750
但是使用该函数创建的结果为5000。而不是4750。 但是当我将这部分悬停时int d = Convert.ToInt32((Discount / 100) * ToDiscount);
没有答案或没有结果。
Discount / 100
正在执行整数除法,结果为0。
因此(Discount / 100) * ToDiscount
也为0,导致从ToDiscount
中不减去任何东西。
我认为您最好的做法是将Discount
的类型更改为decimal
,这将解决您那里的所有问题。
该行:
int d = Convert.ToInt32((Discount / 100) * ToDiscount);
进行整数算术,对于零到99之间的任何折扣, Discount / 100
将为零。
您需要通过十进制或浮点数来应用折扣:
int d = Convert.ToInt32((Discount / 100m) * ToDiscount);
顺便说一句,命名变量Type
可能会引起一些可读性困扰。
当您这样做时:Convert.ToInt32((Discount / 100)* ToDiscount); 您将拥有0,因为:
折扣/ 100 = 0(如果折扣为intm,则结果为int)
您应该使用双数进行计算
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.