C语言对无序数组的查询
发布时间:2023-05-12 12:37:32 所属栏目:语言 来源:
导读:所谓无序数组,就是数组元素的排列没有规律。无序数组元素查询的思路也很简单,就是用循环遍历数组中的每个元素,把要查询的值挨个比较一遍。请看下面的代码:
#include <stdio.h>
int main(){
int nums[10]
#include <stdio.h>
int main(){
int nums[10]
所谓无序数组,就是数组元素的排列没有规律。无序数组元素查询的思路也很简单,就是用循环遍历数组中的每个元素,把要查询的值挨个比较一遍。请看下面的代码: #include <stdio.h> int main(){ int nums[10] = {1, 10, 6, 296, 177, 23, 0, 100, 34, 999}; int i, num, thisindex = -1; printf("Input an integer: "); scanf("%d", &num); for(i=0; i<10; i++){ if(nums[i] == num){ thisindex = i; break; } } if(thisindex < 0){ printf("%d isn't in the array.\n", num); }else{ printf("%d is in the array, it's index is %d.\n", num, thisindex); } return 0; } 运行结果: Input an integer: 100↙ 100 is in the array, it's index is 7. 或者 Input an integer: 28↙ 28 isn't in the array. 这段代码的作用是让用户输入一个数字,判断该数字是否在数组中,如果在,就打印出下标。 第10~15行代码是关键,它会遍历数组中的每个元素,和用户输入的数字进行比较,如果相等就获取它的下标并跳出循环。 注意:数组下标的取值范围是非负数,当 thisindex >= 0 时,该数字在数组中,当 thisindex < 0 时,该数字不在数组中,所以在定义 thisindex 变量时,必须将其初始化为一个负数。 (编辑:汽车网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |