溫馨提示×

c語言如何建立對照表

小億
111
2023-10-27 20:26:49
欄目: 編程語言

在C語言中,可以使用數(shù)組或者結(jié)構(gòu)體來建立對照表。

  1. 使用數(shù)組: 可以使用一個二維數(shù)組來建立對照表。其中,第一維表示需要對照的元素的索引,第二維表示對應(yīng)的值。例如,建立一個字符到整數(shù)的對照表,可以使用如下代碼:
#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\n", output);  // 輸出3

    return 0;
}
  1. 使用結(jié)構(gòu)體: 可以使用一個結(jié)構(gòu)體來存儲需要對照的元素和對應(yīng)的值。例如,建立一個字符串到顏色的對照表,可以使用如下代碼:
#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\n", output);  // 輸出yellow

    return 0;
}

通過以上兩種方式,就可以建立C語言中的對照表。使用數(shù)組可以更方便地通過索引訪問對應(yīng)的值,而使用結(jié)構(gòu)體可以更方便地通過關(guān)鍵字進(jìn)行查找。具體使用哪種方式,可以根據(jù)具體的需求來選擇。

0