您的位置:首页 > 其它

生成一个一维数组,有10个元素,都用随机数填充,用指针轮询的办法实现函数查找一个数是否存在。

2015-01-08 23:11 981 查看
题目:生成一个一维数组,有10个元素,都用随机数填充,用指针轮询的办法实现函数查找一个数是否存在,具体实现代码如下:

[cpp] view
plaincopy





#include <stdlib.h>

#include <stdio.h>

#include <time.h>

int find(int * pInput, int nLen, int nKey, int * pOut)

{

if (!pInput)

{

return 0;

}

if (!pOut)

{

return 0;

}

int * pCurPos = pInput;

int * pEndPos = pInput + nLen;

*pOut = 0;

while (pCurPos < pEndPos)

{

if (*pCurPos == nKey)

{

*pOut = 1;

break;

}

pCurPos++;

}

return 1;

}

int main()

{

int * p = (int *)malloc(sizeof(int)* 10);

if (!p)

{

printf("内存分配失败.\n");

return 0;

}

int i = 0;

srand(time(NULL));

for (i = 0; i < 10; i++)

{

p[i] = rand() % 10;

}

printf("数组元素:\n");

for (i = 0; i < 10; i++)

{

printf("%d ", p[i]);

}

printf("\n");

int nTemp = 0;

int nFind = 0;

printf("请输人要查询的数据:\n");

scanf("%d", &nTemp);

if (find(p, 10, nTemp, &nFind) == 0)

{

printf("查询失败.\n");

}

else

{

if (nFind == 0)

{

printf("未找到元素:%d\n", nTemp);

}

else

{

printf("已经找到元素:%d\n", nTemp);

}

}

if (p)

{

free(p);

}

system("pause");

return 0;

}

运行效果如图1所示:

图1 运行效果
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐