Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to avoid being divided by 0 in C++

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report