How to set accuracy when using double / float type in C ++

In my previous question Comparing doubles and ints, without casting or conversion , I found out how the difference between two doubles discarded the comparison.

I came up with the setprecision () method, which will help display all numbers after the decimal.

Thus, the difference in 6.15 and 3.15 turned out to be equal: 3.00000000000000044408920985006

Now, when it compares with 3, it returns a result saying that it is greater than 3.

How to make it accept only a limited number of digits?

When I used 6.1 and 3.1, the difference was: 2.99999999999999955591079014994

How can I make accuracy so that we know that it is actually 3 and no less.

+3
source share
5

, , / , - . float/double .

setprecision , iomanip , .

- '==', -

bool Compare(double a,double b) {
    std::fabs(a - b) < std::numeric_limits<double>::epsilon();
}

double float integer. float

bool Compare(float a,float b) {
    std::fabs(a - b) < std::numeric_limits<float>::epsilon();
}
+4

. .

, . , a b, , a b eps ( ), - :

if (a - b > eps) {
  // a is greater than b
} else {
  // a is not greater than b
}

, , a b , eps, - :

if (std::abs(a - b) <= eps) {
  // a and b are equal within the set tolerance
} else {
  // a and b are not equal within the set tolerance
}

, ++ . std:: abs, std:: numeric_limits, SO.

+3

, , LSB .

bool Compare(double a, double b)
{
    return (a <= std::nextafter(b, abs(1.1*b))) && (b <= std::nextafter(a, abs(1.1*a)));
}

std::nextafter ++ 11, . . .

+2

setprecision , . , . <cmath>.

+1

float double . float , double.

    std::cout<<std::setprecision(desired no);

    float a=(desired no);

float. , double. , . Double 15 18 , float 6 9 .

0

All Articles