zoukankan      html  css  js  c++  java
  • 开辟一个二维数组,有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("内存分配失败.
    ");
    		return 0;
    	}
    	int i = 0;
    	srand(time(NULL));
    	for (i = 0; i < 10; i++)
    	{
    		p[i] = rand() % 10;
    	}
    	printf("数组元素:
    ");
    	for (i = 0; i < 10; i++)
    	{
    		printf("%d	", p[i]);
    	}
    	printf("
    ");
    	int nTemp = 0;
    	int nFind = 0;
    	printf("请输人要查询的数据:
    ");
    	scanf("%d", &nTemp);
    	if (find(p, 10, nTemp, &nFind) == 0)
    	{
    		printf("查询失败.
    ");
    	}
    	else
    	{
    		if (nFind == 0)
    		{
    			printf("未找到元素:%d
    ", nTemp);
    		}
    		else
    		{
    			printf("已经找到元素:%d
    ", nTemp);
    		}
    	}
    	if (p)
    	{
    		free(p);
    	}
    	system("pause");
    	return 0;
    }
    运行效果如图1所示:

    图1 运行效果

  • 相关阅读:
    常见业务指标
    1006 换个格式输出整数 (Python)
    1004 成绩排名 (Python)
    1003 我要通过! (Python)
    1008 数组元素循环右移问题 (Python)
    如何使用SSH秘钥链接Github
    在windows下如何正确安装curses模块
    面向数据结构C基础知识点(个人向)
    用Python实现链式调用
    python重点串讲
  • 原文地址:https://www.cnblogs.com/new0801/p/6176910.html
Copyright © 2011-2022 走看看