如果将算术运算符号分配给变量并且需要返回以评估简单的算术问题,我怎么能使用算术运算符号 - >从它在下面的代码中构造的方式。怎么样?或任何其他建议欢迎提前致谢
int arithmeticType();
int main() {
int arithmeticSymbol = arithmeticType();
int x, y;
int result = 0;
srand(time(NULL) );
printf( "Type is: %d\n", arithmeticSymbol );
//how to get result of (x + y)using arithmeticSymbol?????
printf( "The result %d %d %d", 4, arithmeticSymbol, 3 );
return 0;
}
int arithmeticType() {
int type, token;
printf("Select the type of arithmetic operation to perform:\n"
"\t1. Addition.\n\t2. Subtraction.\n\t3. Multiplication.\n\t"
"4. Mixture of all three. --> ");
scanf("%d", &type);
switch ( type ) {
case 1:
token = '+';
break;
case 2:
token = '-';
break;
case 3:
token = '*';
break;
case 4:
//get random value between 1-3
token = rand() % 3 + 1;
if ( token == 1 ) {
token = '+';
}
else if ( token == 2 ) {
token = '-';
}
else {
token = '*';
}
break;
default:
printf("Wrong input");
break;
}
return token;
}
答案 0 :(得分:0)
编写一个函数来应用运算符。你还需要考虑你的类型 - 如果你只是使用整数,像3/2这样的东西可能不会达到预期的效果......
如果是我,我可能会使用enum
而不是ASCII运算符代码。
int getResult(int op1, int op, int op2)
{
int result = 0;
if (op== '+') {
result = op1 + op2;
}
else ...
return result;
}
您可以将其称为:printf( "The result of %d %c %d is: %d", 4, getOperation, 3, getResult(4, getOperation, 3) );
(请注意将操作符打印为%d
,不会按预期执行,名称getOperator
会产生误导。