首页 > 解决方案 > C - Scanf 和 Printf 执行乱序,我不知道为什么

问题描述

我有一个问题,我需要使用 C 中的函数指针编写一个菜单驱动程序。用户选择 1-3 选项,如果响应 = 1 则执行加法,如果响应 = 2 则执行减法,如果响应 = 3 则执行乘法。

第一次运行是完美的,但是一旦我循环并尝试进行第二次计算,它会在显示您所做的选择之前搜索选择和第一个数字。

每个函数中的数学运算都有效,传递变量有效,只是 printf 和 scanf 语句在第一次运行后出现故障。

(有减法和乘法函数,它们完全一样,除了分别用“-”和“*”运算符代替“+”运算符。)

我搜索了一个与此类似的问题并尝试了 fflush 和 setvbuf 命令,这些都不起作用。

void addition(int num1, int num2);
void subtraction(int num1, int num2);
void multiplication(int num1, int num2);

int main(void) {
    void(*m[3])(int, int) = { addition, subtraction, multiplication };

    size_t choice;
    int num1, num2;
    printf_s("Would like to add, subtract, or multiply?\nType 1 for 
addition, 2 for subtraction, 3 for multiplication.\n");
    scanf_s("%d", &choice);
    printf_s("what two numbers would you like to work with?\n");
    scanf_s("%d", &num1);
    scanf_s("%d", &num2);
        if (choice >= 1 && choice <= 3) {
        (*m[choice - 1])(num1, num2);
        while (choice >= 1 && choice <= 3) {

            printf_s("Would like to add, subtract, or multiply?\nType 1 
for addition, 2 for subtraction, 3 for multiplication.\n");
            choice = 0;
            scanf_s("%d\n", &choice);
            printf_s("what two numbers would you like to work with?\n");
            scanf_s("%d", &num1);
            scanf_s("%d", &num2);
            (*m[choice - 1])(num1, num2);
        }
        printf("execution complete");
    }
    return 0;
}

void addition(int num1, int num2) {
    int i = 0;
    i = num1 + num2;
    printf("%d + %d = %d\n", num1, num2, i);
    }

如果我输入以下内容:1 2 3, 2 3 1,我希望输出为

"1"

"What two numbers would you like to work with?"

"2"

"3" 
"2+3=5" 
"would you like to add, subtract, or multiply?" 
"Type 1 (...) for multiplication" 
"2" 
"what two numbers (...)" 
"3" 
"1" 
"3-1 =2"

但是我明白了:

"1" 
"What two numbers would you like to work with?"
"2" 
"3" 
"2+3=5" 
"would you like to add, subtract, or multiply?" 
"Type 1 (...) for multiplication"
"2" 
"3" 
"what two numbers (...)" 
"1" 
"3-1 =2"

如您所见,数学是正确的,但第二次需要 2 个数字才能要求 2 个数字。我看不出这是怎么可能的,因为在执行以下 printf 语句之前只扫描了一个变量。即使我乘以的“3”保存在 num1 中,它在 printf 之前扫描,即使语句在 printf 之后,所以这应该是不可能的。我很混乱!

标签: cfunctionpointersprintfscanf

解决方案


我会这样做:

int main(void) {
    void(*m[3])(int, int) = { addition, subtraction, multiplication };
    size_t choice = 1;
    int num1, num2;
    while (choice >= 1 && choice <= 3) {
        printf_s("Would like to add, subtract, or multiply?\nType 1 for addition, 2 for subtraction, 3 for multiplication.\n");
        choice = 0;
        scanf_s("%d", &choice);
        printf_s("what two numbers would you like to work with?\n");
        scanf_s("%d", &num1);
        scanf_s("%d", &num2);
        (*m[choice - 1])(num1, num2);
    }
    return 0;
}

你的问题是 - 你有scanf_s("%d\n", &choice);- 你应该在没有 \n 的情况下做到这一点 -scanf_s("%d", &choice);你可以更轻松地完成循环。删除 if 并将选项设置为 1。


推荐阅读