首页 > 解决方案 > 在 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”?

标签: c++

解决方案


我做了一个格式化响应的函数:

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 个数字、结果和操作,它是一个字符串。


推荐阅读