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

标签 c

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

这样:

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

相关文章:

检查字符串中元音的出现

c++ - 线程间并发无锁?

c - 取消引用指向不完整类型的指针 - typedef struct

c - 什么地方适合定义查找表?

c - 如何在 64 位 Windows 上用 C 代码发出 0x2D 中断?

c - 使用 CBLAS/LAPACK 的 C 语言对称矩阵求逆

python - C 程序可以有 Python GUI 吗?

c++ - 函数调用顺序

c - bmp 图像到 c 中的矩阵(二维数组)

c - Lua 5.3-整数-type()-lua_type()