【发布时间】:2013-10-29 23:20:10
【问题描述】:
下面的程序应该演示使用指向函数的指针数组。一切都很好,除了改变 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);
}
【问题讨论】:
-
试试
%lf而不是%f -
scanf工作正常。您没有正确实施它。 -
程序中正确使用了空格。当我将它复制到 Stack Overflow 上时,我不得不准备一堆东西让它显示在灰色的代码部分中,结果它最终搞砸了空白。
-
只是一点:'printf("%s", "[0] add\n");' - 你为什么要这样做?
-
@Rob:实际上,正确的做法是
printf("%s\n", "[0] add");。以printf("[0] add\n");的身份进行操作通常不是一个好主意。printf的格式参数专门用于格式说明符。一旦您开始将通用字符串塞入该参数,您就会冒着创建意外“格式说明符”的风险(例如,意外使用了%)。因此,通常建议将通用字符串放入printf的进一步参数中,并在格式中使用%s。
标签: c arrays function pointers