2010-06-13 19 views
1

简单的问题,我认为,我是一个有点不确定,为什么分成fractors在C#

decimal currentPercentage = 0; 

currentPercentage = currentPercentage*((decimal)1/(decimal)daysPerYear--);//or 
currentPercentage *= ((decimal)1/(decimal)daysPerYear--); 

将返回0每次但

(decimal)1/(decimal)daysPerYear--; 

将返回我后的位数。我在这里错过了什么?

+0

什么是fractor? – Robaticus 2010-06-13 14:57:09

+2

之前的海报都解决了你的问题,但我无法抗拒提供一些个人建议:考虑查看你的类型,所以你不必一直抛出所有的东西。对于文字1,使用1M使其成为小数。另外,在计算中使用递减运算符( - )相当容易出错。您的代码可能会有益于您在单独的声明中递减。 – Jakob 2010-06-13 15:02:34

回答

6

你0.

currentPercentage相乘是0计算前:

currentPercentage = currentPercentage*((decimal)1/(decimal)daysPerYear--); 

所以,你必须在事实:

currentPercentage = 0 * ((decimal)1/(decimal)daysPerYear--); 

这种表达是0无论什么((decimal)1/(decimal)daysPerYear--)是:)

+0

好吧,这是我的欢呼无聊! – Shane 2010-06-13 15:06:31

0
decimal currentPercentage = 0; 

不管你用零乘什么,其结果将是零......

1

设置decimal currentPercentage = 1;,你会用0您情况下成倍增加。 1是乘法中的中性元素,而不是0.

1

你确定你不想总结,而不是乘以百分比。如果你正在循环并累积百分比,那么求和会更合适。如果你真的要增加,你需要从1开始,而不是从零开始。

顺便说一句,你真的应该使用十进制常量,而不是将整数常量转换为十进制。

var currentPercentage = 0M; 
currentPercentage += (1M/(decimal)daysPerYear--); 

var currentPercentage = 1M; 
currentPercentage *= (1M/(decimal)daysPerYear--);