#include <stdio.h>

int main() { int arr[10]; int x; int i, count = 0; int flag = 1;

// 输入10个整数保存到数组中
for(i=0; i<10; i++) {
    scanf('%d', &arr[i]);
}

// 输入查询的整数x
scanf('%d', &x);

// 查询整数x在数组中出现的位置
for(i=0; i<10; i++) {
    if(arr[i] == x) {
        if(flag) {
            printf('index is: ');
            flag = 0;
        }
        printf('%3d', i);
        count++;
    }
}

// 如果未查询到,输出'Not Found'
if(count == 0) {
    printf('Not Found');
}

return 0;

}

你可以在循环中添加一个标志变量来控制是否输出'index is:'。可以参考下面的代码:

#include <stdio.h>

int main() {
    int arr[10];
    int x;
    int i, count = 0;
    int flag = 1;

    // 输入10个整数保存到数组中
    for(i=0; i<10; i++) {
        scanf('%d', &arr[i]);
    }

    // 输入查询的整数x
    scanf('%d', &x);

    // 查询整数x在数组中出现的位置
    for(i=0; i<10; i++) {
        if(arr[i] == x) {
            if(flag) {
                printf('index is: ');
                flag = 0;
            }
            printf('%3d', i);
            count++;
        }
    }

    // 如果未查询到,输出'Not Found'
    if(count == 0) {
        printf('Not Found');
    }

    return 0;
}

这样,只会在输出数字前输出一次'index is:'。


原文地址: https://www.cveoy.top/t/topic/pmHh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录