下面的程序应该演示使用指向函数的指针数组。一切都很好,除了改变 num1 和 num2 值的 scanf 语句(我在代码中对它们进行了注释)。如果我初始化变量并让它们等于 2,那么当我运行程序时,无论我在 scanf 中输入什么来替换值,它们的值都将为 2。对此的任何帮助将不胜感激!
#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);
}