嘿,我想知道如何将字符“+”变成运算符。例如,如果我有
char op = '+'
cout << 6 op 1;
谢谢。
简单的方法是使用 switch 语句
switch (op)
{
case '+':
res = x + y;
break;
case '-':
res = x - y;
break;
case '*':
res = x * y;
break;
}
我不认为有一种方法,就像你在那里写的那样,但你可以做一些 hacky 之类的事情
int do_op(char op, int a, int b)
{
switch(op)
{
case '+':
return a+b;
break;
case '-':
return a-b;
break;
case '*':
return a*b;
break;
case '/':
return a/b;
break;
default:
throw std::runtime_error("unknown op")
}
}
您可以使用老式的#define:
#define op +
std::cout << 6 op 1;
然而,它的用途有限。
如果您想在纯 C++ 中执行此操作,则必须显式或在外部库中使用 switch 语法(如 tetzfamily.com/temp/EvalDoc.htm 或 codeproject.com/Articles/7939/C-based-Expression-评估库))。
另一种方法是使用外部程序,例如 bc:
char op = '+';
std::string s;
s += "6";
s += op;
s += "4";
system(("echo " + s + "|bc").c_str());
public class ArithmeticOps {
static int testcase11 = 11;
static int testcase12 = 3;
static char testcase13 = '/';
public static void main(String args[]){
ArithmeticOps testInstance = new ArithmeticOps();
int result = testInstance.compute(testcase11,testcase12,testcase13);
System.out.println(result);
}
public int compute(int a, int b,char operator){
int i=0;
switch(operator)
{
case '+' :
i= a+b;
break;
case '-' :
i= a-b;
break;
case '*' :
i= a*b;
break;
case '/' :
i= a/b;
break;
case '%' :
i= a%b;
break;
case '^' :
i= a^b;
break;
default:
i=0;
}
return i;
}
}