c++ - 在 C++ 中的另一个函数中使用函数的参数?
问题描述
我用 c++ 做了一个简单的计算器,我有不同的函数来做、加、减、除和乘。问题是它不是问题只是一个代码清理问题我的所有代码都在运行。所以这是我的代码
#include <iostream>
void sum(int a, int b)
{
int result = a + b;
std::cout << "The result of sum of " << a << " and " << b << " is: " << "\"" << result << "\"" << std::endl;
}
void subtract(int a, int b)
{
int result = a - b;
std::cout << "The result of subtraction of " << a << " and " << b << " is: " << "\"" << result << "\"" << std::endl;
}
void multiply(int a, int b)
{
int result = a * b;
std::cout << "The result of multiplication of " << a << " and " << b << " is: " << "\"" << result << "\"" << std::endl;
}
void divide(int a, int b)
{
int result = a / b;
std::cout << "The result of division of " << a << " and " << b << " is: " << "\"" << result << "\"" << std::endl;
}
int main()
{
int a, b, result;
char symbol;
std::cout << "Enter a number: ";
std::cin >> a;
std::cout << "Enter an operator: ";
std::cin >> symbol;
std::cout << "Enter another number: ";
std::cin >> b;
if (symbol == '+') sum(a, b);
else if (symbol == '-') subtract(a, b);
else if (symbol == '*') multiply(a, b);
else if (symbol == '/') divide(a, b);
else std::cout << "Invalid Operator. Try using the four fundamental operators +, -, *, /" << std::endl;
system("pause");
}
在这里,在我的每个加法、减法、乘法和除法的函数中......std::cout << "The result of sum of " << a << " and " << b << " is: " << "\"" << result << "\"" << std::endl;
这行是一种重复我想把这行作为一个函数并使用参数 a 和 b 你明白了我希望我的代码是与使这条线成为另一个功能一样,我该怎么做?如果我以正常方式执行此操作,那么我将如何告诉我的函数关于“a”和“b”?
解决方案
我做了一个格式化响应的函数:
void printResult (int a, int b, int result, string op)
{
std::cout<<"The result of "<<op<<" of "<<a<<" and "<<b<<" is: "<<result;
}
因此,您必须修改每个函数,如下所示:
void sum(int a, int b)
{
int result = a + b;
printResult(a, b, result, "sum")
}
void substract(int a, int b)
{
int result = a - b;
printResult(a, b, result, "substraction");
}
依此类推......所以对于函数 printResult 的参数是 2 个数字、结果和操作,它是一个字符串。
推荐阅读
- ios - 从后台检查
- excel - Excel vba PasteSpecial xlAdd循环
- javascript - 如何使此滚动内容高于内容 120 像素?
- c# - 将数据添加到实体框架中的动态表
- python - 吉他音符的Python FFT频率
- python - selenium add_cookie 需要两个请求
- android - 检测 RecyclerView 内 Recyclerview 的点击
- ios - iOS UICollectionView 推送刷新时的意外行为
- c# - 从辅助监视器获取像素颜色的更快方法是什么?
- python - 我应该如何将 base.css 与 Django 中的 base.html 文件链接?