C++简单的编程题 从键盘输入任意三个数 用模板函数实现从小到大排序后输出 用c++语言

如题所述

template<class T> T g(T a, T b)
{
if(a>b){return b;}
else return a;

}

void main()

{
int a,b,c;
cin>>a>>b>>c;

while(a==b||a==c||b==c){cout<<"请重新输入"<<endl; cin>>a>>b>>c;} //判断是否有输入相等的数。

if(g(g(a,b),c)==a) //首先判断最小数是否是变量a
{ if(g(b,c)==b) //如果最小数是a,则再判断最小数是否是b,如果是就知道从小到到顺序为abc了
{cout<<"从小到大排序为a,b,c"<<endl;}
else //否则,从小到大的顺序就为acb
{cout<<"从小到大排序为a,c,b"<<endl;}
}

if(g(g(a,b),c)==b) //与上一个if原理类似
{ if(g(a,c)==a){cout<<"从小到大排序为b,a,c"<<endl;}
else{cout<<"从小到大排序为b,c,a"<<endl;}
}

if(g(g(a,b),c)==c)
{ if(g(a,b)==b){cout<<"从小到大排序为c,b,a"<<endl;}
else{cout<<"从小到大排序为c,a,b"<<endl;}
}

system("pause");
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-03-13
#include<iostream>
using namespace std;
template<class T>
void display(T &a,T &b,T &c)
{
T temp;
if(a>b)
{
temp=a;
a=b;
b=temp;
}
if(a>c)
{
temp=a;
a=c;
c=temp;
}
if(b>c)
{
temp=b;
b=c;
c=temp;
}
}
int main()
{
double a1,b1,c1;
cout<<"输入任意三个数"<<endl;
cin>>a1>>b1>>c1;
display(a1,b1,c1);
cout<<"排序后的顺序为:"<<endl;
cout<<a1<<" "<<b1<<" "<<c1<<endl;
return 0;
}
第2个回答  2010-03-13
#include <iostream>

using namespace std;

void paiXu(int &a, int &b)
{
int temp;
if( a > b )
{
temp = a;
a = b;
b = temp;
}
}

void main()
{
int a,b,c;
cout << "Please input three numbers." << endl;
cin >> a >> b >> c;
paiXu(a,b);
paiXu(a,c);
paiXu(b,c);
cout<< a << "\t"<< b << "\t" << c;
}

vs2008下编译通过
相似回答