Find pair and odd in variable float language C

Asked

Viewed 1,548 times

3

Is there a bug in my program when I try to find the odd and odd pair 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);
}
  • 2

    Look, if this is a college exercise, just know that the teacher(a) may have a soul or a brain, but not both. Parity is a property of integer numbers only. Integers do not have parity.

3 answers

2

Floating point number does not provide accuracy, then its equality occurs in some cases, but not in the majority. That’s just one of the reasons why you can’t use it for monetary value.

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

Credits: Maniero

One way to fix this is by converting the float for int, but I don’t know if it’ll be helpful in your situation.

Or make a if to check between 2 numbers, 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;
}

2

Can’t.

Parity (the property of being even or odd) is unique to whole numbers. Variables of the type float represent numbers by approximation - will never represent an integer, as Francis said.

If you want to delve into this, the Math Stack (in English) has explanations about because parity does not apply to non-integer numbers. The answer marked as correct is very complex for those who have not completed a mathematics faculty, but there are simpler answers that are equally satisfying.

The ideal is to work with integers, not floating point numbers. But if you go that way, better than capturing a number as a floating point and converting it to integer is already capturing as integer (%d instead of %f in his scanf).

-3

The solution I found was a=value_float;

If the float value is, for example:

2.0000, will receive 2

1.5, will receive 1

I think it already does

Browser other questions tagged

You are not signed in. Login or sign up in order to post.