帮我写一个程序,功能是查找当前数在数组中的位置
时间: 2024-02-13 13:02:17 浏览: 23
好的,以下是一个查找数组中指定数值位置的示例程序:
```python
def find_position(arr, target):
"""
在数组中查找指定数值位置的函数
参数:
arr: 数组
target: 要查找的数值
返回值:
如果找到目标数值,则返回其在数组中的位置,否则返回 -1
"""
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
# 测试
arr = [1, 3, 5, 7, 9]
target = 5
pos = find_position(arr, target)
if pos != -1:
print("目标数值在数组中的位置为: ", pos)
else:
print("未找到目标数值")
```
在这个示例程序中,我们定义了一个名为 `find_position` 的函数,接受两个参数:要查找的数组和目标数值。函数遍历整个数组,如果找到目标数值,则返回其在数组中的位置。如果遍历完整个数组都没有找到目标数值,则返回 -1。最后我们使用示例数组和目标数值来测试这个函数,并根据返回值输出结果。
相关问题
帮我用C语言写一个程序,功能是查找当前数在数组中的位置
好的,以下是一个用C语言实现查找数组中指定数值位置的示例程序:
```c
#include <stdio.h>
int find_position(int arr[], int size, int target) {
/*
在数组中查找指定数值位置的函数
参数:
arr: 数组
size: 数组大小
target: 要查找的数值
返回值:
如果找到目标数值,则返回其在数组中的位置,否则返回 -1
*/
int i;
for (i = 0; i < size; i++) {
if (arr[i] == target) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 5, 7, 9};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int pos = find_position(arr, size, target);
if (pos != -1) {
printf("目标数值在数组中的位置为: %d\n", pos);
} else {
printf("未找到目标数值\n");
}
return 0;
}
```
在这个示例程序中,我们定义了一个名为 `find_position` 的函数,接受三个参数:要查找的数组、数组的大小和目标数值。函数遍历整个数组,如果找到目标数值,则返回其在数组中的位置。如果遍历完整个数组都没有找到目标数值,则返回 -1。主函数中我们使用示例数组和目标数值来测试这个函数,并根据返回值输出结果。
用java写一个查找一个数x在数组中出现的次数程序
好的,可以这样实现:
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数组长度:");
int n = scanner.nextInt();
int[] arr = new int[n];
System.out.println("请输入数组元素:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}
System.out.print("请输入要查找的数:");
int x = scanner.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
count++;
}
}
System.out.println(x + "在数组中出现的次数为:" + count);
}
}
```
这段代码首先从键盘输入数组长度和数组元素,然后再输入要查找的数x。接着通过循环遍历数组,如果当前元素等于要查找的数x,则计数器加1。最后输出x在数组中出现的次数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)