c语言编程(把这批数据用数组存储):在一批数据中查找给定值的位置。
时间: 2024-05-16 17:14:17 浏览: 14
以下是一个简单的C语言程序,用于在给定的数组中查找一个特定的值,并返回其位置(如果存在):
```c
#include <stdio.h>
int main() {
int arr[10] = {2, 5, 7, 8, 3, 9, 4, 1, 6, 0};
int search_val = 7;
int i, pos = -1;
for (i = 0; i < 10; i++) {
if (arr[i] == search_val) {
pos = i;
break;
}
}
if (pos != -1) {
printf("The value %d was found at position %d.", search_val, pos);
} else {
printf("The value %d was not found in the array.", search_val);
}
return 0;
}
```
在这个例子中,我们首先创建一个大小为10的整数数组,并将一些值存储在其中。然后,我们定义一个要查找的值(在本例中为7),并使用一个循环来遍历整个数组。如果我们找到了要查找的值,我们将其位置存储在变量`pos`中,并使用`break`语句退出循环。最后,我们检查`pos`的值,如果它不是-1,则找到了要查找的值。否则,我们的程序将告诉我们它没有找到它。