C++简单函数困境

c++ simple function dilemma

本文关键字:困境 函数 简单 C++      更新时间:2023-10-16

我正在学习c++。这是我的问题:

简单的"计算器"程序:读取两个数字和一个符号,将它们传递给函数 calculate,如果禁止字符输入,则返回值或错误。我想出了我的函数的两个版本,我不知道哪个是"正确的"。他们在这里:

第一个直接打印,这不是一个好的做法(是吗?

void calculate(int x, int y, char s) {
switch (s) {
case ('+'): {
std::cout << x + y << "n";
}
case ('-'): {
std::cout << x - y << "n";
}
case ('*'): {
std::cout << x * y << "n";
}
case ('/'): {
std::cout << x / y << "n";
}
default: {
std::cout << "Wrong sign input. Choose on of the following four:+-*/n";
}
}
}

第二个只做一个工作,有一个缺陷:例如,如果输入是'5'、'6'和'-',它将返回-1,并且它将被调用者作为错误处理。

int calculate(int x, int y, char s) {
switch (s) {
case ('+'): {
return x + y;
}
case ('-'): {
return x - y;
}
case ('*'): {
return x * y;
}
case ('/'): {
return x / y;
}
default: {
return -1;
}
}
}

在给定的情况下,您会怎么做?

您可以使用返回值来返回操作结果或状态代码,但不能同时返回两者(除非您使用特殊值,我会避免这样做。 如何使用状态的返回值,并在输出参数中设置结果?

int calculate(int x, int y, char s, int & result); // returns: 0 - success; -1 - failure

你有几个更好的选择。

  1. 引发异常
  2. 退货std::numeric_limits<int>::max()
  3. 将实际结果放在指针/引用传递的变量中,并使用返回值作为状态

我会选择例外。

default:
throw std::invalid_argument(std::string("invalid operator: ") + s);

首先,将计算与输出计算结果分开是个好主意。

谈到如何处理错误输入的问题...

能够返回状态和结果的另一种方法是使用std::pair作为返回类型。

std::pair<bool, int> calculate(int x, int y, char s)
{
...
}

并确保成功案例返回{true, result},不成功案例返回{false, 0}

输出和计算应该是单独的函数。但是,如果它也可以是有效的输出值,则不应使用特殊的哨兵值来指示错误。

真正的问题是,输入验证和计算应该是不同的功能。我会为潜在的操作创建一个enum,并将其传递进来。

enum class Operation {
ADD,
SUBTRACT,
MULTIPLY,
DIVIDE
};

然后calculate接受一个Operation.您仍然需要在某处验证输入,但它不应该在同一个地方。

calculate中,您仍然需要一个default情况,因为enum可以具有声明的值以外的值,但是由于您应该在其他地方验证输入,因此您可以将其设置为简单的assert

编辑:

处理错误的正确方法是投掷和接球。这是一个版本。

#include <iostream>
#include <stdexcept>
using std::cout;
using std::cin;
using std::cerr;
using std::invalid_argument;
int calculate(int, int, char);
int main()
{
int num1, num2;
char symbol;
cin >> num1 >> num2 >> symbol;
try {
cout << calculate(num1,num2,symbol) << 'n';
} catch (const invalid_argument& error) {
cout << error.what() << 'n';
return 1;
}
return 0;
}
int calculate(int x, int y, char s) {
switch (s) {
case '+':
return x + y;
case '-':
return x - y;
case '*':
return x * y;
case '/':
return x / y;
default:
throw invalid_argument("Received non existing option!");
}
}

还有一个没有抛出的版本。

这是代码的工作版本。

#include <iostream>
using std::cout;
using std::cin;
using std::cerr;
int calculate(int, int, char);
int main()
{
int num1, num2;
char symbol;
cin >> num1 >> num2 >> symbol;
cout << calculate(num1,num2,symbol) << 'n';
return 0;
}
int calculate(int x, int y, char s) {
switch (s) {
case '+':
return x + y;
case '-':
return x - y;
case '*':
return x * y;
case '/':
return x / y;
default:
cerr << "Unrecognised option!n";
return -1;
}
}

我也稍微改变了格式。随意探索它,如果您有任何与代码相关的问题,请询问。

回答这个问题:更喜欢第二种方式。这是正确的方法。