📄 fig2.cpp
字号:
#include <iostream>
using namespace std;
#define Sentinel -1;
int MaxElements=250;
/************************函数声明****************************/
void GiveInstructions();
int GetIntegerArray(int array[]);
void ReverseIntegerArray(int array[], int n);
void SortIntegerArray(int array[], int n);
void PrintIntegerArray(int array[], int n);
/*************************主函数*****************************/
int main()
{
int array[250];
int n;
GiveInstructions();
n = GetIntegerArray(array);
cout << "The reverse array is as follows: " << endl;
ReverseIntegerArray(array, n);
PrintIntegerArray(array, n);
cout << "The sorted array is as follows: " << endl;
SortIntegerArray(array, n);
PrintIntegerArray(array, n);
return 0;
}
/***********************提示信息*****************************/
void GiveInstructions()
{
cout << "Enter numbers, one per line, ending with the\n"
<< "sentinel value -1 The program will then\n"
<< "display those values in reverse order and sorted order.\n";
}
int GetIntegerArray(int array[])//从用户获得数组中的元素
{
for (int i = 0; i < MaxElements; i++)
array[i] = 0;
cout << " ? ";
cin >> array[0];
int n = 1;
while (n < MaxElements)
{
cout << " ? ";
cin >> array[n];
if (array[n] != -1)
{
int t = 0;
while (t < n)
{
if (array[t] == array[n])
break;
else
t++;
}
if (t<n)
cout << array[n] << " is already in the array. Please input again." << endl;
else
n++;
}
else
{
n = n-1;
break;
}
}
return n;
}
/*************************将数组中的元素倒倒序**************************/
void ReverseIntegerArray(int array[], int n)
{
for (int p = 0; 2 * p < n + 1; p++)
{
int temp = array[p];
array[p] = array[n - p];
array[n - p] = temp;
}
}
/***********************将数组中的元素由小到大排列*********************/
void SortIntegerArray(int array[],int n)
{
int MinIndex; /* 最小元素的下标 */
int pass, j; /* 用来扫描数组的下标 */
int temp; /* 用来交换数组元素的临时变量 */
for (pass = 0; pass < n; pass++)/* 从下标pass开始扫描数组 */
{
MinIndex = pass;
for (j = pass + 1;j <= n;j++)
{
if (array[j] < array[MinIndex])
MinIndex = j;/* 如果找到更小元素,将该位置赋给minIndex */
}
if (MinIndex != pass)
{
temp = array[pass];
array[pass] = array[MinIndex];
array[MinIndex] = temp;
}
}
}
/******************************打印数组*****************************/
void PrintIntegerArray(int array[], int n)
{
for (int i = 0; i <= n; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
/*********************************************************************/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -