[I'm new to C programming and I have this assignment that requires me to design a program that asks a user to guess a value and then the program will calculate the derived value from the input using a mathematic equation given in the assignment. The problem I'm having is that after the user enters the value, it is not assigned to the variable and as a result I keep getting weird values when I printf the input value. For e.g
Code:
int main {
double x;
printf ("Please guess a value: ");
calculate (x);
.
.
.
return 0;
}
calculate (double x) {
char buf[20];
char *p;
if (fgets (buf, sizeof(buf), stdin) != NULL) {
x = strtod (buf, &p);
if (buf[0] != '\n' && (*p == '\n' || *p == '\0')) {
if (x > 0) {
printf ("Value = %d", x);
}
}
}
}
The above is similar to part of my code. It appears that the value entered is not assigned to the variable x after the input is deemed valid using fgets. I'm not sure why is this so so can anyone tell me what's wrong with my code?