繁体   English   中英

在C#中分解为分式

[英]Dividing into fractors in C#

我认为这是一个简单的问题,我不确定为什么

decimal currentPercentage = 0;

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

每次都会返回0

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

将返回我要的小数。 我在这里想念什么?

您乘以0。

在计算之前, currentPercentage0

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

因此,您实际上有:

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

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

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

您确定不想对百分比求和,而不是相乘。 如果您是循环执行并累加百分比,则求和会更合适。 如果您真的要相乘,则需要从1开始,而不是零。

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

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

要么

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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