在C#中划分为分形

时间:2010-06-13 14:52:23

标签: c#

简单的问题我想,我有点不确定为什么

decimal currentPercentage = 0;

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

每次都会返回0

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

将返回我之后的小数。我在这里缺少什么?

4 个答案:

答案 0 :(得分:6)

你乘以0.

计算之前

currentPercentage 0

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

所以你实际上是:

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

无论 0 是什么,此表达式都是 ((decimal)1 / (decimal)daysPerYear--) :)

答案 1 :(得分:1)

设置decimal currentPercentage = 1;,因为在您的情况下,您将乘以0。 1是乘法中的中性元素,而不是0。

答案 2 :(得分:1)

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

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

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

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

答案 3 :(得分:0)

decimal currentPercentage = 0;

无论你乘以零乘以什么,结果都是零......