有没有办法让编译器将运算符视为+, - ,/或*的真正含义?以下不起作用。
#include <stdio.h>
int main(void) {
int number1=10, number2=5;
char operator;
int result=0;
printf("Enter Operator ");
scanf("%c",&operator);
if (operator=='+')
result=number1+operator+number2;
printf("%d",result);
}
答案 0 :(得分:3)
此:
result=number1+operator+number2;
根据您的想法,永远不会在C
中工作。当您实际将ascii
的{{1}}代码添加到+
和number1
时。
所以,我想做以下事情:
number2
这样可以获得正确的结果。
答案 1 :(得分:2)
没有。 C不是JavaScript。它没有运行时评估功能。如果你想解析和评估数学表达式,那么你必须做一些更复杂的事情,比如this guy did。
答案 2 :(得分:2)
不,C是一种静态类型语言。你不能这样做。
您可以做的是,要求用户选择操作,并根据用户输入,您可以使用开关盒来执行用户建议的操作。
答案 3 :(得分:1)
不,C不能那样做。
或者:
if (operator=='+')
result=number1+number2;
答案 4 :(得分:1)
operator
的值是一个字符,而不是函数或运算符。您不能只解释在运行时输入的字符,作为编译程序时构建的程序的一部分。
请改为:
if (operator == ’+') return number1 + number2;
答案 5 :(得分:1)
我担心你必须在交换机或语句中处理每个操作符:
switch(operator){
case '+': // Note that this works only for scalar values not string
result = number1+number2;
// ...
}
Alliteratively你可以准备这样的操作员回调列表:
typedef int (*operator_callback) (int operand1, int operand2);
typedef struct {
char name;
operator_callback callback;
} operator_definition;
int operator_add(int x, int y) {return x+y;}
int operator_minus(int x, int y) {return x-y;}
// And prepare list of those
operator_definition[] = {
{'+', operator_add},
{'-', operator_minus},
{NULL, NULL}
};
// Function for fetching correct operator callback
operator_callback get_operator_callback(char op)
{
int i;
for( i = 0; operator_definition[i].name != NULL; ++i){
if( operator_definition[i].name == op){
return operator_definition[i].callback;
}
}
return NULL;
}
// And in main function
operator_callback clbk = get_operator_callback(operator);
if( !clbk){
printf( "Unknown operator %c\n", operator);
return -1;
}
result = clbk(number1, number2);