除以零且没有错误? [英] Divide by zero and no error?

查看:93
本文介绍了除以零且没有错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅出于某种原因,我只是进行了一次简单的测试,除了我想尝试对我所有方法进行测试之外,尽管这很简单,或者我想。

Just threw together a simple test, not for any particular reason other than I like to try to have tests for all my methods even though this one is quite straightforward, or so I thought.

    [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);
    }

正如您在测试方法中看到的那样,我被零除。问题是,它不会产生错误。请参见下面的错误窗口显示。

As you can see in the test method, I AM dividing by zero. The problem is, it doesn't generate an error. See the error window display below.

< img src = https://i.stack.imgur.com/Fjx6O.png alt =来自VS2017的错误列表视图>

错误给出无穷大的值?我想念的是什么?所以我搜寻了一下,发现双精度数除以零不会产生错误,它们给出的是空值或无穷大。问题变成了,如何测试无穷大返回值?

Instead of an error it is giving a value of infinity? What am I missing?So I googled and found that doubles divided by zero DON'T generate an error they either give null or infinity. The question becomes then, how does one test for an Infinity return value?

推荐答案

您将拥有 DivideByZeroException 仅在整数值的情况下:

You are going to have DivideByZeroException only in case of integer values:

int total = 3;
int numberOf = 0;

var tot = total / numberOf; // DivideByZeroException thrown 

如果至少一个参数是浮点数 (问题中的 double ),结果为 FloatingPointType.PositiveInfinity double.PositiveInfinity ),无一例外

If at least one argument is a floating point value (double in the question) you'll have FloatingPointType.PositiveInfinity as a result (double.PositiveInfinity in the context) and no exception

double total = 3.0;
int numberOf = 0;

var tot = total / numberOf; // tot is double, tot == double.PositiveInfinity

这篇关于除以零且没有错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆