mercredi 26 décembre 2018

Pointer compared to a number in an if-statement in C

I've got a question. I'm currently trying to solve an exercise my university gave us but something isn't working as it should be.

I have to implement a function which checks whether a number (entered by the user) is in the range of -2.5 and 2.5. If yes, it should save the number at the address of the pointer and return 0. If not, it should clear the buffer and return 1. We do not have to check for any buffer errors and we have to make sure that the value at the address of the pointer is not changed in an error.

We also have to write the main-function, which reads in the number and prints out error reports when the user enters a number which is not in the range.

Right now, I wrote both of the functions, except for the error reports in case of a wrong entered number. I didn't do that because there's in another mistake I made which is more important now than the missing text for errors. When I try my program and enter a number which is not in the range it still says that the given number is in the range. I think my mistake is in the if-statement with the pointer comparison. We did pointers in uni only a week ago, so I'm not that experienced when it comes to using them in code.

Here is my code:

#include <stdio.h>

int read_interval (double *p)
{
    int c;

    if (*p < -2.5 || *p > 2.5) {
            while ((c = getchar()) != '\n') {}
            return 1;
    } else {
            *p = *p;
            return 0;
    }
}

int main ()
{
    double number, *p;

    printf("Please enter a number between -2.5 and 2.5: ");
    scanf("%d", &number);

    p = &number;

    int status = read_interval(p);

    printf("%i", status);

    return 0;

}

I hope somebody here can help me out. I really want to improve my skills in C. Thank you in advance.

Alex

Aucun commentaire:

Enregistrer un commentaire