Dan*_*don 4 c# exception overflow
我有一些代码,它将一个参数作为一个Dictionary并返回一个Dictionary.
代码计算所有double值的总和,并使用该值计算每个值与总和的百分比.它返回一个新的Dictionary,其百分比连接到键上.
我的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;
}
Run Code Online (Sandbox Code Playgroud)
干得好:
addPercentagesToDataPointLabels(new Dictionary<string, double>(){{"a", 0}});
Run Code Online (Sandbox Code Playgroud)
就像gdoron所说的那样,你除以0.但是它只针对整数抛出异常.对于浮点数,它会导致Double.Infinity.然后它尝试将无穷大转换为十进制.
| 归档时间: |
|
| 查看次数: |
387 次 |
| 最近记录: |