[英]discount calculation in c# error on assigning value
Can someone tell whats wrong with my code? 有人可以告诉我我的代码有什么问题吗?
I've already tried casting first the value but I get the same result. 我已经尝试过先转换值,但得到的结果相同。
/// <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;
}
Example: 例:
Discount(5000, 5, DiscountType.Percent);
//calculation: (5/100) * 5000 = 250
//discount: 5000 - 250 = 4750
but the with that function I've created I get result 5000. instead of 4750. I did break point on return temp; 但是使用该函数创建的结果为5000。而不是4750。 but when I hover this part
int d = Convert.ToInt32((Discount / 100) * ToDiscount);
但是当我将这部分悬停时
int d = Convert.ToInt32((Discount / 100) * ToDiscount);
no answer or no result. 没有答案或没有结果。
Discount / 100
is performing integer division, in which the result is 0. Discount / 100
正在执行整数除法,结果为0。
Hence (Discount / 100) * ToDiscount
also is 0, resulting in nothing being subtracted from ToDiscount
. 因此
(Discount / 100) * ToDiscount
也为0,导致从ToDiscount
中不减去任何东西。
I think that the best thing for you to do would be to change the type of Discount
to being a decimal
, which would solve all of your problems there. 我认为您最好的做法是将
Discount
的类型更改为decimal
,这将解决您那里的所有问题。
The line: 该行:
int d = Convert.ToInt32((Discount / 100) * ToDiscount);
Does integer arithmetic, where Discount / 100
will be zero for any discount between zero and 99. 进行整数算术,对于零到99之间的任何折扣,
Discount / 100
将为零。
You need to apply the discount via decimal, or floating point: 您需要通过十进制或浮点数来应用折扣:
int d = Convert.ToInt32((Discount / 100m) * ToDiscount);
As an aside, naming a variable Type
is probably going to cause a few readability headaches down the line. 顺便说一句,命名变量
Type
可能会引起一些可读性困扰。
When you make this: Convert.ToInt32((Discount / 100) * ToDiscount); 当您这样做时:Convert.ToInt32((Discount / 100)* ToDiscount); you will have have 0 because:
您将拥有0,因为:
Discount /100 = 0 (if discount is intm the result will be int) 折扣/ 100 = 0(如果折扣为intm,则结果为int)
you should do a calculation with double numbers 您应该使用双数进行计算
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.