// 获取中间值
public static int getMidNum(int a, int b, int c) {
return (a < b ? (b < c ? b : a < c ? c : a) : (b > c ? b : a > c ? c: a));
}
// 获取最大值
public static int getMaxNum(int a, int b, int c) {return (a < b ? (b < c ? c : b) : (a < c ? c : a));
}
// 获取最小值
public static int getMinNum(int a, int b, int c) {
return (a > b ? (b > c ? c : b) : (a > c ? c : a));
}
例子: 编写主函数,提示用户通过键盘输入一个3位整数,判断是否为有效输入,调用一个子函数,取出该整数的各个位数并重新排列,输出可能的最大整数和最小整数。
// 获取最大数字
int const& getMaxNum(int const& x, int const& y, int const& z);
// 获取最小数字
int const& getMinNum(int const& x, int const& y, int const& z);
// 获取中间数字
int const& getMidNum(int const& x, int const& y, int const& z);
// 数字的新组合
void getNewCombination(int const& num);
// 数字的新组合
void getNewCombination(int const& num)
{
int hBit; // 百位
int tBit; // 十位
int oBit; // 个位
int max = 0,min = 0;
int t = 0;
hBit = num / 100;
tBit = (num/10)%10;
oBit = ((num%100)%10);
max = getMaxNum(hBit, tBit, oBit);
min = getMinNum(hBit, tBit, oBit);
t = getMidNum(hBit,tBit,oBit);
cout<<"The Maximum num is : " << (max*100 + t*10 + min)<<endl;
cout<<"The Minimum num is : " << (min*100 + t*10 + max)<<endl;
}
// 获得最大的数字
int const& getMaxNum(int const& x, int const& y, int const& z)
{
int temp = (x>y)? x : y;
return temp > z ? temp : z;
}
// 求中间大小的数字
int const& getMidNum(int const& x, int const& y, int const& z)
{
return (x < y ? (y < z ? y : x < z ? z : x) : (y > z ? y : x > z ? z : x));
}
// 获取最小的数
int const& getMinNum(int const& x, int const& y, int const& z)
{
int temp = (x<y)? x : y;
return temp<z ? temp : z;
}
void main()
{
int num;
do
{
cout<<"请输入一个三位数 : ";
cin>>num;
if (num < 100 || num > 1000)
{
MessageBox(NULL,"数值范围为100--999","提示",MB_OK);
}
} while (num < 100 || num > 1000);
getNewCombination(num);
cout<<endl;
}