函数中的Scanf重复输入请求两次

时间:2017-11-16 07:16:38

标签: c function scanf

//Main Function of Calculator Project
int main (void)
{
        int input, result, result1, result2, result3, result4;

        printf ("===================================\n");
        printf ( "WELCOME TO THE CALCULATOR PROJECT\n");
        printf ("===================================\n\n");

        printf ("Option 1. ADDITION\n");
        printf ("Option 2. SUBTRACTION\n");
        printf ("Option 3. MULTIPLICATION\n");
        printf ("Option 4. DIVISION\n\n");

        printf ("Enter Option:>> ");
        scanf  ("%d", &input);

        switch (input)
        {
                case 1:
                        addition(result1);
                        printf ("Result: %d\n", addition(result1));
                        break;
                case 2:
                        subtraction(result2);
                        printf ("Result: %d\n", subtraction(result2));
                        break;
                case 3:
                        multiplication(result3);
                        printf ("Result: %d\n", multiplication(result3));
                        break;
                case 4:
                        division(result4);
                        printf ("Result: %d\n", division(result1));
                        break;
                default:
                        printf ("Invalid Input\n");
 }
           return 0;

}

当程序运行时,它会返回正确的计算,但无论用户函数是什么运行,总是要求输入两次。

1 个答案:

答案 0 :(得分:2)

您正在调用要求输入的函数并执行两次计算:

case 1:
    addition(result1); // You first call it here
    printf ("Result: %d\n", addition(result1)); // You call it again here
    break;

您还传递了一个未初始化的变量作为参数。该变量应该用于保存返回值,而不是作为参数。

因此,您只需调用一次,将结果分配给变量,然后打印该变量。

int result = -1;
case 1:
    result = addition();
    break;
case 2:
    result = subtraction();
    break;
case 3:
    result = multiplication();
    break;
case 4:
    result = division();
    break;
default:
    printf("Invalid input\n");
}
printf("Result: %d\n", result);