简体   繁体   English

在C#中分解为分式

[英]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 每次都会返回0

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

will return the decimal I am after. 将返回我要的小数。 What am I missing here? 我在这里想念什么?

You're multiplying by 0. 您乘以0。

currentPercentage is 0 before computing: 在计算之前, currentPercentage0

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 :) 无论((decimal)1 / (decimal)daysPerYear--)是什么,此表达式均为0

Set decimal currentPercentage = 1; 设置decimal currentPercentage = 1; as you would be multiplying by 0 in your case. 因为您将要乘以0。 1 is the neutral element in multiplication, not 0. 1是乘法的中性元素,而不是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. 如果您真的要相乘,则需要从1开始,而不是零。

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;

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

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

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