Why if (a == 2.3) evaluates to false when float a = 2.3

#include<stdio.h>

void main()
{
    float a = 2.3;
    if(a == 2.3) {
        pritnf("hello");
    }
    else {
        printf("hi");
    }
}

It prints "hi" at the output, or we can say that if the condition gets a false value.

#include<stdio.h>

void main()
{
    float a = 2.5;
    if(a == 2.5)
        printf("Hello");
    else
        printf("Hi");
}

Sends greetings.

+4
source share
3 answers

A variable ais one floatthat has some value close to mathematical value 2.3.

2.3 double, , 2.3, double , float, a. float double , , .

a == 2.3 float double. ( ), , , 2.3.

, :

assert(a == 2.3f);
//             ^
+12

2.3 01000000000100110011001100110011... float 2.3 : 2.299999952316284

double float, :

float a = 2.3;

if, float a double 2.299999952316284

:

float a = 2.3f;

:

if (a == 2.3f) {
    ...
}

:

if (fabs(a - 2.3f) < 0.00001) {
    ...
}

2.5, : 01000000001000000000000000000000

EDIT: fabs <math.h> <cmath>

:

+3

, , float .

, ( ). 2 , (epsilon):

if( fabs(a - 2.3f) < epsion) { ... }

where epsilon is small enough for your calculation, but not too small (more Machine epsilon ).

0
source

Source: https://habr.com/ru/post/1655323/


All Articles