/*
* 輸入10個整數,將其中最小的數與第一個數對換,把最大的數與最后一個數對換。
* 編寫3個函數:(1)輸入10個數;(2)進行處理;(3)輸出10個數。
*/
#include<iostream>
using namespace std;
/*
* 用符號常量定義數組長度(const:constant)
*
* 說明:
* 由於使用 const 語句定義符號常量帶有數據類型,以便系統進行類型檢查,
* 同時該語句具有計算初值表達式和賦初值的功能,所以比宏命令(#define)定義符號常量要優越得多,
* 因此提倡使用 const 語句。
*/
const int arrayLength=10;
void main()
{
void inputNum(int number[],int temp_length);
void outputNum(int number[],int temp_length);
void swap(int number[],int temp_length);
int number[arrayLength];
cout<<"請輸入10個整數:"<<endl;
//number為數組地址
inputNum(number,arrayLength);
swap(number,arrayLength);
outputNum(number,arrayLength);
}
/*
* 輸入整數
*/
void inputNum(int number[],int temp_length)
{
int length=0;
length=temp_length;
for(int i=0;i<length;i++)
{
cin>>number[i];
}
}
/*
* 交換
*/
void swap(int number[],int temp_length)
{
int *max,*min,*pointer,temp,length;
//將數組首地址賦值給指針變量,即指針變量指向數組的第一個元素
max=min=number; //因為是右結合,所以這樣寫;一右而不右,三右賦值右
temp=0;
length=temp_length;
/*
* 循環變量初始值:數組第2個值的地址;循環條件:數組最后一個值的地址(number+length-1);循環變量增值:地址+1
*/
for(pointer=number+1;pointer<number+length;pointer++)
{
if(*pointer>*max)
{
//將大數地址賦給max
max=pointer;
}
else if(*pointer<*min)
{
//將小數地址賦給min
min=pointer;
}
}
//將最小數與第一個數交換
temp=number[0];
//把指針變量min所指向的值賦值給number數組的第一個值;
//'*':為指針運算符
number[0]=*min;
*min=temp;
//將最大數與最后一個數交換
temp=number[9];
number[9]=*max;
*max=temp;
}
/*
* 輸出整數
*/
void outputNum(int number[],int temp_length)
{
int length=0;
length=temp_length;
for(int i=0;i<length;i++)
{
cout<<number[i]<<"\t";
}
}
運行結果:

備注:指針變量所占空間大小由地址總線決定。
