如何使用数组索引作为运算符?
这样:
#include<stdio.h>
main()
{
char sign[]={'+','-'};
int a, b;
a = 12 sign[1] 10;
printf("%d",a);
}
实际上这段代码不起作用。此类程序的正确代码是什么?
最佳答案
最简单的是使用 switch 语句或 if-else 链。
#include<stdio.h>
int main() {
char sign[]={'+','-'};
int a,b;
switch (sign[1]) {
case '+':
a = 12 + 10;
break;
case '-':
a = 12 - 10;
break;
}
printf("%d",a);
}
如果我这样做,我最终可能会把一些逻辑移到一个函数中。也许是这样的:
#include<stdio.h>
int perform_operation(char op, int lhs, int rhs) {
switch (op) {
case '+':
return lhs + rhs;
case '-':
return lhs - rhs;
default:
return 0;
}
}
int main() {
char sign[]={'+','-'};
int a = perform_operation(sign[1], 12, 10);
printf("%d",a);
}
关于c - 如何使用数组索引作为运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26718585/