如何使用数组索引作为一个经营者? [英] How to use an array index as an operator?
本文介绍了如何使用数组索引作为一个经营者?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用数组索引作为一个经营者?
How to use an array index as an operator?
使得:
#include<stdio.h>
main()
{
char sign[]={'+','-'};
int a, b;
a = 12 sign[1] 10;
printf("%d",a);
}
其实这code不起作用。什么将是正确的code为这种类型的节目?
Actually this code doesn't work. What will be the right code for this type of programs?
推荐答案
最简单的就是使用switch语句或的if-else链。
The simplest is to use a switch statement or if-else chain.
#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);
}
如果我这样做,我可能最终会移动一些逻辑成一个函数虽然。也许是这样的:
If I was doing this, I'd probably end up moving some of the logic into a function though. Perhaps something like this:
#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);
}
这篇关于如何使用数组索引作为一个经营者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文