How to avoid being divided by 0 in C++
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.