The program below is supposed to demonstrate using an array of pointers to functions. Everything works great, except the scanf statements that change the value of num1 and num2 (I have them commented in the code). If I initialize the variables and have them equaling, say, 2, then when I run the program their value's will be 2 regardless of what I enter in scanf to replace the value. Any help with this would be greatly appreciated!
#include <stdio.h>
// function prototypes
void add (double, double);
void subtract (double, double);
void multiply (double, double);
void divide (double, double);
int main(void)
{
// initialize array of 4 pointers to functions that each take two
// double arguments and return void.
void(*f[4])(double, double) = { add, subtract, multiply, divide };
double num1; // variable to hold the 1st number
double num2; // variable to hold the 2nd number
size_t choice; // variable to hold the user's choice
printf("%s", "Which operation would you like to perform on the two numbers?\n");
printf("%s", "[0] add\n");
printf("%s", "[1] subtract\n");
printf("%s", "[2] multiply\n");
printf("%s", "[3] divide\n");
printf("%s", "[4] quit\n");
scanf_s("%u", &choice);
// process user's choice
while (choice >= 0 && choice < 4)
{
printf("%s", "Enter a number: ");
scanf_s("%f", &num1); // <--- THIS SCANF_S STATEMENT ISN'T CHANGING NUM1'S VALUE
printf("%s", "Enter another number: ");
scanf_s("%f", &num2); // <--- THIS SCANF_S STATEMENT ISN'T CHANGING NUM2'S VALUE
// invoke function at location choice in array f and pass
// num1 and num2 as arguments
(*f[choice])(num1, num2);
printf("%s", "Which operation would you like to perform on the two numbers?\n");
printf("%s", "[0] add\n");
printf("%s", "[1] subtract\n");
printf("%s", "[2] multiply\n");
printf("%s", "[3] divide\n");
printf("%s", "[4] quit\n");
scanf_s("%u", &choice);
} // end while loop
puts("Program execution completed");
} // end main
void add(double a, double b)
{
printf("%1.2f + %1.2f = %1.2f\n", a, b, a + b);
}
void subtract(double a, double b)
{
printf("%1.2f - %1.2f = %1.2f\n", a, b, a - b);
}
void multiply(double a, double b)
{
printf("%1.2f * %1.2f = %1.2f\n", a, b, a * b);
}
void divide(double a, double b)
{
printf("%1.2f / %1.2f = %1.2f\n", a, b, a / b);
}
As others have said, use the correct format specifiers.
1) When using scanf()
, "%f"
is for float
and "%lf"
is for double
.
double num1;
// scanf_s("%f", &num1);
scanf_s("%lf", &num1);
2) The use of "%u"
may work given your platform, but size_t
and unsigned
are not necessarily the same size. With C11, (and maybe C99) use the z
modifier.
size_t choice;
// scanf_s("%u", &choice);
scanf_s("%zu", &choice);
3) It is always good to check the result from scanf_s()
.
if (1 != scanf_s(...)) {
; // handle_error();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.