下面的程序应该演示使用指向函数的指针数组。一切都很好,除了更改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);
}
答案 0 :(得分:0)
正如其他人所说,使用正确的格式说明符。
1)使用scanf()
时,"%f"
用于float
而"%lf"
用于double
。
double num1;
// scanf_s("%f", &num1);
scanf_s("%lf", &num1);
2)"%u"
可能在您的平台上使用,但size_t
和unsigned
的大小不一定相同。使用C11,(可能是C99)使用z
修饰符。
size_t choice;
// scanf_s("%u", &choice);
scanf_s("%zu", &choice);
3)从scanf_s()
检查结果总是好的。
if (1 != scanf_s(...)) {
; // handle_error();
}