我的代码将一个字典作为参数并返回一个字典。
代码计算所有 double 值的总和,并使用总和计算每个值占总和的百分比。它返回一个新的字典,其中百分比连接到键上。
我的 Web 服务器的事件查看器中记录了一些 OverflowExceptions。日志记录异常发生在以下代码 Decimal percentage = (Decimal) (pDataPoints[key]/sum * 100);
表示在将值转换为小数时发生异常。
我可能会遗漏什么极端情况?
public static Dictionary<string, double> addPercentagesToDataPointLabels(Dictionary<string, double> pDataPoints)
{
Dictionary<string, double> valuesToReturn = new Dictionary<string, double>();
// First, compute the sum of the data point values
double sum = 0;
foreach (double d in pDataPoints.Values)
{
sum += d;
}
// Now, compute the percentages using the sum and add them to the new labels.
foreach (string key in pDataPoints.Keys)
{
string newKey = key;
Decimal percentage = (Decimal) (pDataPoints[key] / sum * 100);
percentage = Math.Round(percentage, ChartingValues.DIGITS_AFTER_DECIMAL_POINT);
newKey += " " + percentage.ToString() + "%";
valuesToReturn.Add(newKey, pDataPoints[key]);
}
return valuesToReturn;
}
最佳答案
给你:
addPercentagesToDataPointLabels(new Dictionary<string, double>(){{"a", 0}});
就像 gdoron 说的,你除以 0。但它只为整数抛出异常。对于 float ,结果为 Double.Infinity
。然后它会尝试将无穷大转换为小数。
关于c# - 计算百分比时抛出 OverflowException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10417029/