0

下面的程序应该演示使用指向函数的指针数组。一切都很好,除了改变 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);
}
4

1 回答 1

0

正如其他人所说,使用正确的格式说明符。

1) 当使用scanf(), "%f"is forfloat"%lf"is for 时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();
}
于 2013-10-30T04:39:37.690 回答