C :为什么它总是首先执行最后一个参数

c++: why does it always do the last parameter first?

本文关键字:执行 最后一个 参数 为什么      更新时间:2023-10-16

所以我只是使用函数编写一个简单的计算器,我想尽可能容易地使用。我基本上希望您可以在1行代码中进行询问数字和计算的整个过程,还可以计算结果。但是我有问题。在下面的代码中,当我在主要功能中执行" cout<<计算(askcalculation(),asknumber1(),asknumber2())<< endl;''''''然后我运行该程序,然后我希望它首先询问计算,然后询问第一个数字,然后询问第二个数字。但这并不是这样做的,实际上它以反对性的方式来做到这一点。有什么原因,我该如何解决?

哦,我知道您只能将3个询问效果放在1堂课中,以使其更加简单,但是有什么方法可以将计算功能放在同一班级中?

#include <iostream>
using namespace std;
int calculate(int calculation, int firstNumber, int lastNumber)
{
    switch(calculation)
    {
    case 1:
        return firstNumber + lastNumber;
        break;
    case 2:
        return firstNumber - lastNumber;
        break;
    case 3:
        return firstNumber * lastNumber;
        break;
    case 4:
        return firstNumber / lastNumber;
        break;
    }
}
int askNumber1()
{
    int a;
    cout << "Give the first number" << endl;
    cin >> a;
    return a;
}
    int askNumber2()
{
    int b;
    cout << "Give the second number" << endl;
    cin >> b;
    return b;
}
int askCalculation()
{
    int c;
    cout << "what calculation do you want to do? add (1) subtract (2) multiplication (3) divide (4)" << endl;
    cin >> c;
    return c;
}
int main()
{
    cout << calculate(askCalculation(), askNumber1(), askNumber2()) << endl;
    return 0;
}

函数参数的评估顺序未在C或C 中定义。如果您需要特定的顺序,请按所需的顺序分配这些函数的返回值,然后将这些变量传递给该函数:

int a = askCalculation();
int b = askNumber1();
int c = askNumber2();
cout << calculate( a, b, c ) << endl;