注册 登录
编程论坛 C++教室

请各位帮忙简化算法

a874695162 发布于 2014-07-21 21:15, 341 次点击
//输入四个int 将它们按从大到小的顺序输出
#include "stdafx.h"
#include<iostream>
using namespace std;
int main()
{
    void sort(int a,int b,int c,int d);
    int a,b,c,d;
    cout<<"输入四个要排序的数字,中间用空格隔开。"<<endl;
    cin>>a>>b>>c>>d;
    sort(a,b,c,d);
    return 0;
}
void sort(int a,int b,int c,int d)
{
    int t;
    if(a<b){t=a;a=b;b=t;}
    if(c<d){t=c;c=d;d=t;}
    cout<<"已将四个数从大到小排序:"<<endl;
    if(b>c)cout<<a<<","<<b<<","<<c<<","<<d<<endl;
    if(d>a)cout<<c<<","<<d<<","<<b<<","<<a<<endl;
    if(a>c&&d>b)cout<<a<<","<<c<<","<<d<<","<<b<<endl;
    if(c>a&&b>d)cout<<c<<","<<a<<","<<b<<","<<d<<endl;
    if(d>b&&c>a&&a>d)cout<<c<<","<<a<<","<<d<<","<<b<<endl;
    if(b>d&&c>b&&a>c)cout<<a<<","<<c<<","<<b<<","<<d<<endl;
}

该程序的算法是否可以简化?
2 回复
#2
rjsp2014-07-22 08:32
程序代码:
#include <iostream>
#include <utility> // C++11之前std::swap定义在<algorithm>中,之后定义在<utility>中
using namespace std;

void sort4int( int& a, int& b, int& c, int& d );

int main()
{
    int a, b, c, d;
    cout << "输入四个要排序的数字,中间用空格隔开。" << endl;
    cin >> a >> b >> c >> d;

    sort4int( a, b, c, d );
    cout << "已将四个数从大到小排序:" << endl;
    cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << endl;

    return 0;
}

void sort4int( int& a, int& b, int& c, int& d )
{
    if( a > b ) std::swap( a, b );
    if( c > d ) std::swap( c, d );
    if( a > c ) std::swap( a, c );
    if( b > d ) std::swap( b, d );
    if( b > c ) std::swap( b, c );
}
#3
a8746951622014-07-22 08:49
回复 2 楼 rjsp
多谢指点,初学者,以后多有请教!
1