算法实例_简单数组数字查找 By:比方

 

在某一个数组内查找指定的数字,如果找到了该数据,则打印出该数据的所属位置信息,

反之,如果未找到,则打印出未找到提示信息。

 

逻辑判断流程如下所示

变量x  = 输入需要查找的数据

变量arr = 随机生成的数组数据

 

循环 1 to 30;

判断 数组[元素] == x

打印 ‘找到数据’

打印 ‘未找到数据’

 

使用C语言代码为:

 

 1 // ArrFirst.cpp : Defines the entry point for the console application.
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <stdlib.h>
 6 #include <time.h> /*用到了time函数,所以要有这个头文件*/
 7 
 8 int main(int argc, char* argv[])
 9 {
10     int x = 0;
11     int arr[20] = {0};
12     int i;
13 
14     srand((unsigned) time(NULL)); /*种子*/
15 
16     printf("产生出的随机数\r\n");
17     for(i = 1 ; i <= 20 ; i++){
18         arr[i] = rand()/1000;
19         printf("%d\t",arr[i]);
20     }
21 
22     printf("输入需要查找的数值:\r\n");
23 
24     scanf("%d",&x);
25 
26     for(i = 1 ; i <= 20 ; i++){
27         if(arr[i] == x){
28             printf("数据%d 在数组的第%d个元素中找到数据\r\n",x,i);
29             break;
30         }
31     }
32 
33     system("pause");
34 
35     return 0;
36 }

 

附件下载地址:http://pan.baidu.com/s/1c04D4jQ

posted @ 2014-07-30 10:48  比方  阅读(191)  评论(0)    收藏  举报