din*_*tom 48 c# divide-by-zero
只是把一个简单的测试扔到一起,不是出于任何特殊原因,除了我想尝试对我的所有方法进行测试,即使这个非常简单,或者我认为.
[TestMethod]
public void Test_GetToolRating()
{
var rating = GetToolRating(45.5, 0);
Assert.IsNotNull(rating);
}
private static ToolRating GetToolRating(double total, int numberOf)
{
var ratingNumber = 0.0;
try
{
var tot = total / numberOf;
ratingNumber = Math.Round(tot, 2);
}
catch (Exception ex)
{
var errorMessage = ex.Message;
//log error here
//var logger = new Logger();
//logger.Log(errorMessage);
}
return GetToolRatingLevel(ratingNumber);
}
Run Code Online (Sandbox Code Playgroud)
正如您在测试方法中看到的那样,我将其除以零.问题是,它不会产生错误.请参阅下面的错误窗口显示.
而不是错误,它给出无穷大的价值?我错过了什么?所以我用谷歌搜索,发现双倍除以零不要产生错误,他们要么给出无效或无穷大.那么问题就是,如何测试Infinity的返回值?
Dmi*_*nko 79
你将有DivideByZeroException只有在的情况下,整数值:
int total = 3;
int numberOf = 0;
var tot = total / numberOf; // DivideByZeroException thrown
Run Code Online (Sandbox Code Playgroud)
如果至少有一个参数是浮点值(double在问题中),那么你将拥有FloatingPointType.PositiveInfinity(double.PositiveInfinity在上下文中)并且没有异常
double total = 3.0;
int numberOf = 0;
var tot = total / numberOf; // tot is double, tot == double.PositiveInfinity
Run Code Online (Sandbox Code Playgroud)
小智 6
你可以检查如下
double total = 10.0;
double numberOf = 0.0;
var tot = total / numberOf;
// check for IsInfinity, IsPositiveInfinity,
// IsNegativeInfinity separately and take action appropriately if need be
if (double.IsInfinity(tot) ||
double.IsPositiveInfinity(tot) ||
double.IsNegativeInfinity(tot))
{
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10808 次 |
| 最近记录: |