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

  • 相关阅读:
    leetcode 337. House Robber III
    leetcode 366 Find Leaves of Binary Tree
    leetcode 250 Count Univalue Subtrees
    leetcode 132 Palindrome Pairs 2
    leetcode 131 Palindrome Pairs
    leetcode 336 Palindrome Pairs
    leetcode 214 Shortest Palindrome
    leetcode 9 Palindrome Number
    Socket编程
    Zookeeper
  • 原文地址:https://www.cnblogs.com/new0801/p/6176910.html
Copyright © 2011-2022 走看看