[英]How Get Discount-Percentage In C#
let suppose dis.text = 2, prc.text = 100, I am using these codes.It Should be net_prc.text = 98.But its giving me -100.Can anybody tell me why?,And how can i get correct discounted percentage?? 假设dis.text = 2,prc.text = 100,我正在使用这些代码。应该是net_prc.text = 98.但是它给了我-100。有人可以告诉我为什么吗?百分比??
private void net_prcTabChanged(object sender, EventArgs e)
{
int d;
int di;
int i;
d = Convert.ToInt32(dis.Text);
i = Convert.ToInt32(prc.Text);
di = -((d / 100) * i) + i;
net_prc.Text = di.ToString();
}
di = -((d / 100) * i) + i;
All values in this statement are Integers. 该语句中的所有值都是Integers。 You are going to be computing arithmetic with decimal places, and you need to increase the precision of your variables to a double or a float.
您将要使用小数位进行算术运算,并且需要将变量的精度提高到双精度或浮点型。 Instead, add a decimal place to one of the values in the equation.
而是,将小数位添加到公式中的值之一。 This will force all values into doubles.
这将强制所有值翻倍。
This is a process called Arithmetic Promotion . 这是一个称为算术提升的过程。 It is where, at run time, the precision of every variable in an equation is increased to the size of the most precise variable.
在运行时,方程式中每个变量的精度都会增加到最精确变量的大小。
尝试(d / 100.0)强制其使用浮点算法
正确的方法是将di
的数据类型更改为float
di = (d * 100) / i;
C# has an odd way of doing maths, because your numbers are cast as integers, you can only do integer math with them. C#有一种奇怪的数学方法,因为您的数字被强制转换为整数,因此您只能对它们进行整数数学运算。 you need to initially have them as float or as double so you can do float math or anything at all that requires a decimal place within the calculations.
您最初需要将它们设置为float或double,以便可以进行float数学运算或在计算中需要小数点的所有内容。
Even dis.text = 1.5 甚至dis.text = 1.5
private void net_prcTabChanged(object sender, EventArgs e)
{
double d;
double di;
double i;
d = Convert.ToDouble(dis.Text);
i = Convert.ToDouble(prc.Text);
di = -((d * 100.0) / i ) + i;
net_prc.Text = di.ToString();
}
Your division, d / 100
, is a division of integers, and it returns an integer, probably 0
(zero). 您的除法
d / 100
是整数的除法,它返回一个整数,可能为0
(零)。 This is certainly the case with your example d = 2
. 您的示例
d = 2
肯定是这种情况。
Addition: If you really want to do this with integers (rather than changing to decimal
or double
like many other answers recommend), consider changing the sub-expression 加法:如果您真的想使用整数(而不是像其他许多建议的那样更改为
decimal
或double
精度),请考虑更改子表达式
((d / 100) * i)
into 进入
((d * i) / 100)
because it will give you a better precision to do the division as the last operation. 因为这样做会为您提供更好的精度,将其作为最后一个操作进行除法。 With the numbers of your example,
d=2
and i=100
, the first sub-expression will give 0*100
or 0
, while the changed sub-expression yields 200/100
which will be 2
. 使用示例中的数字
d=2
和i=100
,第一个子表达式将给出0*100
或0
,而更改后的子表达式将产生200/100
,即2
。 However, you will not get rounding to nearest integer; 但是,您将不会舍入到最接近的整数。 instead you will get truncating (fractional part is discarded no matter if it's close to
1
). 取而代之的是,您将被截断(小数部分接近
1
都将被丢弃)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.