?? 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 + -