gpt4 book ai didi

c - 如何使用数组索引作为运算符?

转载 作者:行者123 更新时间:2023-12-04 10:45:27 25 4
gpt4 key购买 nike

如何使用数组索引作为运算符?

这样:

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com