简体   繁体   中英

Dividing into fractors in C#

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

decimal currentPercentage = 0;

currentPercentage = currentPercentage*((decimal)1 / (decimal)daysPerYear--);//or
currentPercentage *= ((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;

无论您乘以零,结果都将为零...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM