开发者

Dividing into fractors in C#

开发者 https://www.devze.com 2023-01-03 19:59 出处:网络
Simple question I think, I am a little unsure as to why decimal currentPercentage = 0; currentPercentage = currentPercentage*((decimal)1 / (decimal)daysPerYear--);//or

Simple question I think, I am a little unsure as to why

decimal currentPercentage = 0;

currentPercentage = currentPercentage*((decimal)1 / (decimal)daysPerYear--);//or
开发者_如何学GocurrentPercentage *= ((decimal)1 / (decimal)daysPerYear--);

Will return 0 everytime but

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

will return the decimal I am after. What am I missing here?


You're multiplying by 0.

currentPercentage is 0 before computing:

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

So you have in fact:

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

This expression is 0 no matter what ((decimal)1 / (decimal)daysPerYear--) is :)


Set decimal currentPercentage = 1; as you would be multiplying by 0 in your case. 1 is the neutral element in multiplication, not 0.


Are you sure you don't want to sum, not multiply, the percentages. If you're doing this in a loop and accumulating percentages, summing would be more appropriate. If you really are going to multiply, you need to start with 1, not zero.

BTW, you really should be using decimal constants, rather than casting an integer constant to decimal.

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

or

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


decimal currentPercentage = 0;

No matter what you multiply with zero, the result will be zero...

0

精彩评论

暂无评论...
验证码 换一张
取 消