租用问题

质量为本、客户为根、勇于拼搏、务实创新

< 返回租用问题列表

c语言怎么建立对照表,C语言怎么建立数组

发布时间:2023-10-27 20:26:49

c语言怎样建立对比表

在C语言中,可使用数组还是结构体来建立对比表。

  1. 使用数组: 可使用一个二维数组来建立对比表。其中,第一维表示需要对比的元素的索引,第二维表示对应的值。例如,建立一个字符到整数的对比表,可使用以下代码:
#include <stdio.h>

int main() {
    char chars[] = {'a', 'b', 'c', 'd', 'e'};
    int nums[] = {1, 2, 3, 4, 5};
    int length = sizeof(chars) / sizeof(chars[0]);

    char input = 'c';
    int output;

    for (int i = 0; i < length; i++) {
        if (chars[i] == input) {
            output = nums[i];
            break;
        }
    }

    printf("%d
", output);  // 输出3

    return 0;
}
  1. 使用结构体: 可使用一个结构体来存储需要对比的元素和对应的值。例如,建立一个字符串到色彩的对比表,可使用以下代码:
#include <stdio.h>
#include <string.h>

typedef struct {
    char* str;
    char* color;
} Mapping;

int main() {
    Mapping mappings[] = {
        {"apple", "red"},
        {"banana", "yellow"},
        {"orange", "orange"}
    };
    int length = sizeof(mappings) / sizeof(mappings[0]);

    char* input = "banana";
    char* output;

    for (int i = 0; i < length; i++) {
        if (strcmp(mappings[i].str, input) == 0) {
            output = mappings[i].color;
            break;
        }
    }

    printf("%s
", output);  // 输出yellow

    return 0;
}

通过以上两种方式,就能够建立C语言中的对比表。使用数组可以更方便地通过索引访问对应的值,而使用结构体可以更方便地通过关键字进行查找。具体使用哪一种方式,可以根据具体的需求来选择。