Find even and odd in float language variable C

3

There are some errors in my program when I try to find the odd and even of a float variable.

#include<stdio.h>
#include<string.h>
void exe7(float vet[]){
    int i;

    for(i=0;i<5;i++){
        scanf("%f",&vet[i]);
    }

    for(i=0;i<5;i++){
        if(vet[i] %2 ==0){
            vet[i+5]=vet[i]+0.02;
        }
        if(vet[i] %2 !=0){
            vet[i+5]=vet[i]+0.05;//vet[i+5] pois será armazenado em outra posição;
        }
    }
    for(i=0;i<10;i++){
        printf("%f",vet[i]);
    }
}
main(){
    float vet[10];

    exe7(vet);
}
    
asked by anonymous 14.07.2017 / 15:26

2 answers

2

Floating-point number does not provide accuracy , so its equality occurs in some cases, but not in most cases . This is just one of the reasons why you can not use it for monetary value.

No palliative solution is good . What you can do is normalize, that is, treat as if it were a fixed point by doing conversion to integer according to the desired scale.

Credits: bigown

One way to fix this is to convert float to int , but I do not know if it will be useful in your situation.

Or make a if to check between 2 numbers, for example:

if(vet[i] %2 < 0.0001 && vet[i] %2 > -0.0001){
    vet[i+5]=vet[i]+0.02;//vet[i+5] pois será armazenado em outra posição;
}
    
14.07.2017 / 15:33
2

It does not work.

Parity (the property of being even or odd) is unique to integers . Variables of type float represent numbers by approximation - will never represent a whole number, as Francisco spoke.

If you want to dig deeper into this, the Math Stack has explanations about because parity does not apply to non-integer numbers . The correct answer is very complex for those who did not complete a math faculty, but there are simpler answers that are equally satisfactory.

The ideal is to work with integers, not floating-point numbers. But if it goes by that way, rather than catching a number as a floating point and converting it to integer is already capturing as an integer ( %d instead of %f in its scanf ).

    
14.07.2017 / 16:01