溫馨提示×

c語言如何輸出數組中某個值

小億
267
2023-11-13 10:50:34
欄目: 編程語言

在C語言中,可以使用循環遍歷數組,然后通過判斷數組元素是否等于目標值來輸出數組中某個值的索引。

下面是一個示例代碼:

#include <stdio.h>

int main() {
    int array[] = {2, 4, 6, 8, 10};
    int length = sizeof(array) / sizeof(array[0]);
    int target = 6;
    int index = -1; // 初始索引設為-1,表示未找到目標值
    
    // 循環遍歷數組
    for (int i = 0; i < length; i++) {
        // 判斷數組元素是否等于目標值
        if (array[i] == target) {
            index = i; // 記錄目標值的索引
            break; // 找到目標值后跳出循環
        }
    }
    
    // 輸出目標值的索引
    if (index != -1) {
        printf("目標值 %d 在數組中的索引為 %d\n", target, index);
    } else {
        printf("數組中不存在目標值 %d\n", target);
    }
    
    return 0;
}

在上述代碼中,數組 array 中存儲了一些整數,我們要查找的目標值是 target,我們通過循環遍歷數組,判斷數組元素是否等于目標值,如果找到了目標值,則記錄下它的索引,否則索引保持為初始值 -1。

最后,根據索引的值,輸出目標值在數組中的位置。如果索引為 -1,則表示數組中不存在目標值。

運行上述代碼,將輸出:

目標值 6 在數組中的索引為 2

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女