源程序:
#include <iostream>
#include <algorithm>
#include <functional>
#include <iomanip>
#include <stdlib.h>
const int MAXSIZE = 10;
using namespace std;
int *InitArray()
{
int i;
int *p = new int[10]; //动态分配一个10个整数的数组,指针p指向数组的首地址
for (i = 0; i<10; i++)
p[i] = -1; //给数组中的每个单元赋值均为-1
return p; //返回数组的首地址
}
//逆序打印的实现
void reverse(int b[])
{
for (int i = 0; i<MAXSIZE/2; i++)
{
int temp;
temp = b[i];
b[i] = b[MAXSIZE-1 - i];
b[MAXSIZE-1 - i] = temp;
}
}
//在数组中查找值为K的元素
int search(int A[],int n,int k) //因为数组已经逆序了,所以在计算第几个元素
{ //时,是从最后面开始的
int i = 0; //此时,应当从后向前开始数
while (i < n)
{
if (A[i] != k)
i++;
else
break;
}
return i;
}
int main()
{
int a[10]={34,5,8,12,15,35,69,40,33,19};
int *b = InitArray();
int i;
for (i = 0; i < 10; i++)
b[i] = a[i];
cout << "数组中的数为:" << endl;
for (i = 0; i < 10; i++)
cout << setw(4) << a[i];
cout << endl;
cout << "逆序输出数组:"<<endl;
reverse(b);//逆序打印
for (i = 0; i < MAXSIZE; i++)
cout << setw(4) << b[i]; //输出数组中的值
cout << endl;
/*
int *p = b; //用指针输出
for (; p < b + 10; p++)
cout << setw(5) << *p;
*/
int x;
cout << "\n在数组中查找一人数,若找到显示其位置,没找到则显示-1" << endl;
cout << "请输入要查找的数:";
scanf("%d", &x);
int pos = search(a, 10, x);
if (pos < 10)
cout<<"这个数的位置是:"<<pos + 1<<endl;
else
cout<<"-1 没有此数!\n"<<endl;
system("pause");
return 0;
}
运行结果: