在一组数中,顺序查找儿是否在此数组中,若存在则输出" the numberis found!”,若不存在则输出“ the nunber isnot found!"。要求数组长度定义为10,用给定的测试数据对数组初始化。
基于new bing的修改:
你用static干嘛嘞
#include <stdio.h>
#define N 10
int main()
{
int a[N] = {3, 4, 7, 12, 24, 78, 9, 15, 80, 45};
int p = 0, i, x;
for (i = 0; i < N; ++i)
printf("%3d", a[i]);
printf("\n");
printf("Please enter the number to be found: ");
scanf("%d", &x);
while (p < N && x != a[p])
p++;
if (p < N)
printf("%d The number is found at position %d\n", x, p);
else
printf("%d The number is not found\n", x);
return 0;
}
不知道你这个问题是否已经解决, 如果还没有解决的话:解决方案:
我们可以使用遍历数组的方式来查找指定数字是否存在。
首先,我们需要定义一个长度为10的int型数组,并用给定的测试数据对其进行初始化:
int[] arr = {15, 20, 25, 30, 35, 40, 45, 50, 55, 60};
接下来,我们需要定义一个int型变量num存储要查找的数字,假设要查找的数字为35:
int num = 35;
然后,我们使用for循环遍历数组,并在每次循环中判断当前元素是否等于要查找的数字,如果相等,则输出"the number is found!"并返回,否则继续往下遍历,直到遍历完整个数组:
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
System.out.println("the number is found!");
return;
}
}
如果遍历完整个数组仍未找到指定数字,则输出"the number is not found!":
System.out.println("the number is not found!");
完整代码如下:
public class Main {
public static void main(String[] args) {
int[] arr = {15, 20, 25, 30, 35, 40, 45, 50, 55, 60};
int num = 35;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == num) {
System.out.println("the number is found!");
return;
}
}
System.out.println("the number is not found!");
}
}
输出结果为:
the number is found!