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 solve the accuracy problem of C++ floating-point comparison

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces "how to solve the accuracy problem of C++ floating point comparison". In daily operation, I believe many people have doubts about how to solve the accuracy problem of C++ floating point comparison. The editor consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubt of "how to solve the accuracy problem of C++ floating point comparison". Next, please follow the editor to study!

1 introduction

Let me give you an example:

# include

Int main ()

{

Float a = 0.1

Float b = 0.2

Float c = a + b

If (c = = 0.3) {

Printf ("c = = 0.3\ n")

} else {

Printf ("0.1 + 0.2! = 0.3\ n")

}

Return 0

}

C! = 0.3

A _

If the variables a, b for 0.75, 0.5, you can see that the run c = = 1.25, which means that the floating-point operation is unstable.

A quarter of a century, a quarter of a century, a circle of 0.75, a circle of 1.25.

Why it can be good and bad, because not all decimals can be represented by the floating point standard (IEEE 754).

Therefore, judging whether two floating-point variables are equal cannot be simply achieved by the "= =" operator. When floating-point numbers are compared, the difference between them is generally within a certain range.

Bool feq (float a float b) {

Return fabs (afort b)

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