复制代码 代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int size = 0;
int flag = 0;
void output(int *arry)
{
int i = 0;
for(i=0; i<size; i++)
{
printf("arry[%d]=%d\t",i,arry[i]);
if((i+1)%5 == 0)
printf("\n");
}
printf("\n");
}
void getarry(int *arry)
{
int i = 0;
srand(time(NULL));
for(i=0; i<size; i++)
{
arry[i] = rand() % 100;
}
}
void add(int *arry, int pos, int num)
{
int i = 0;
if(pos>=0 && pos<=size)
{
if(pos < size) //在中间插入
{
for(i=size; i>pos; i--)
{
arry[i] = arry[i-1];
}
arry[pos] = num;
}
else //在最后的位置插入
{
arry[size] = num;
}
size++;
}
else
printf("只能在0-%d的位置插入。\n",size);
}
int search(int *arry, int num)
{
static int pos = 0;
if(flag)
pos++;
for(; pos<size; pos++)
{
if(arry[pos] == num)
{
flag = 0;
return pos;
}
}
return -1;
}
void mod(int *arry, int pos, int num)
{
if(pos>=0 && pos<size)
{
arry[pos] = num;
}
else
{
printf("输入位置错误。\n");
}
}
int del(int *arry, int num)
{
int count = 0;
int pos = 0;
int i = 0;
pos=search(arry, num);
while(pos+1)
{
for(i=pos; i<size; i++)
{
arry[i] = arry[i+1];
}
count++;
pos=search(arry, num);
}
return count;
}
int main()
{
//pos 0到size-1
int *arry = NULL;
int count = 0;
int pos = 0;
int num = 0;
printf("输入要产生多少个随机数:");
scanf("%d",&size);
arry = malloc(2*size*sizeof(int));
getarry(arry);
output(arry);
printf("输入要添加的位置(0-%d):",size);
scanf("%d",&pos);
printf("输入要添加的数字:");
scanf("%d",&num);
add(arry, pos, num);
output(arry);
printf("输入要查找的数字:");
scanf("%d",&num);
pos=search(arry, num);
while(pos+1)
{
flag = 1;
count++;
printf("arry[%d]=%d\n",pos, num);
pos=search(arry, num);
}
printf("共找到%d个匹配数字\n",count);
printf("输入要修改的位置:");
scanf("%d",&pos);
printf("输入要修改为数字:");
scanf("%d",&num);
mod(arry, pos, num);
output(arry);
printf("输入要删除的数字:");
scanf("%d",&num);
del(arry, num);
output(arry);
free(arry);
arry = NULL;
return 0;
}