[英]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。
在計算之前, currentPercentage
為0
:
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.