Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to avoid being divided by 0 in C++

Shulou Source: shulou.com Published: 2022-06-02 07:42:59 11月17日 Update

How to avoid being divided by 0 in C++? for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Reason (reason)

The result is undefined and probably a crash.

The result is undefined and is likely to cause the program to crash.

Note (Note)

This also applies to%.

This rule also applies to the remainder operation.

Example, bad (negative example)

Double divide (int a, int b)

{

/ / BAD, should be checked (e.g.in a precondition)

Return a / b

}

Example, good (sample)

Double divide (int a, int b)

{

/ / good, address via precondition (and replace with contracts once C++ gets them)

Expects (b! = 0)

Return a / b

}

Double divide (int a, int b)

{

/ / good, address via check

Return b? A / b: quiet_NaN ()

}

Alternative: For critical applications that can afford some overhead, use a range-checked integer and/or floating-point type.

Optional: for demanding applications that can bear a certain cost, consider using integers or floating-point numbers with range checks.

Enforcement (implementation recommendations)

Flag division by an integral value that could be zero

An integer divisor whose tag may be zero.

This is the answer to the question on how to avoid being divided by 0 in C++. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.

Tags: Clocked questions questions integers more help answers easy easy cost content reason negative guys partners suggestions methods tags points knowledge examples Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Xiaomi macOS Microsoft NVidia Shulou Technology