开辟一个二维数组,有10*8个元素,用随机数填充,按照下面的方法用函数实现查找一个数是否存在...

题目:开辟一个二维数组,有10*8个元素,用随机数填充,按照下面的方法用函数实现查找一个数是否存在。

具体实现如下:

#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 运行效果

转载于:https://www.cnblogs.com/new0801/p/6176910.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值