C :为什么它总是首先执行最后一个参数
c++: why does it always do the last parameter first?
所以我只是使用函数编写一个简单的计算器,我想尽可能容易地使用。我基本上希望您可以在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;
相关文章:
- lower_bound()返回最后一个元素
- 获取向量C++中第一个值和最后一个值的和
- 获取用C/C++打印的最后一个字符串
- 使用运算符 [] 引用 std::vector 上最后一个元素时出现问题<>
- 为什么这个程序返回最后一个单词而不是最长的单词?
- 为什么我的最后一个 ELSE 条件无法正确执行
- Lower_bound不适用于具有 3 个元素的向量的最后一个元素
- 查找数组中第一个最小值和最后一个最大值元素之间的算术平均值
- 仅显示链表的最后一个元素
- 测试迭代器是否位于列表中的最后一个
- push_back通过自行创建的对象获取最后一个元素的向量
- 使用 map.end() 访问 map 的最后一个元素
- 如何知道地图中的最后一个元素是否被删除?
- std::矢量保存 只推送最后一个元素
- 反转后不返回最后一个元素
- 如何删除矢量中的重复值,最后一个除外
- 递归推动POP POSTFIX计算器无法正确执行操作,只需将最后一个数字作为结果
- CMake 意外地将最后一个文件名预置到可执行文件中
- C :为什么它总是首先执行最后一个参数
- 写入数组时,最后一个线程的执行速度比第一个线程慢