第十七周项目2-引用作形参

设计一个程序,输入3个整数,将其按从大到小的顺序输出,要求
(1)排序功能通过函数实现,3个整数用3个变量,不必定义数组;

(2)写出两个版本的函数,一个采用传地址值的方法,另一个采用引用类型作参数

/*
* Copyright (c) 2014,烟台大学计算机学院
* All right reserved.
* 作者:邵帅
* 文件:demo.cpp
* 完成时间:2014年12月17日
* 版本号:v1.0
*/
#include <iostream>
using namespace std;
void sort(int &x, int &y, int &z);
void sort2(int *x, int *y, int *z);
int main()
{
    int a, b, c;
    int d, e, f;
    cout<<"将使用引用法排序,请输入:";
    cin >> a >> b >> c;
    sort(a, b, c);
    cout << "引用排序后的数字为:" << a << " " << b << " " << c<<endl;
    cout<<"将使用指针法排序,请输入:";
    cin >> d >> e >> f;
    sort2(&d, &e, &f);
    cout << "指针排序后的数字为:" << d << " " << e << " " << f<<endl;
    return 0;
}

void sort(int &x, int &y, int &z)
{
    int temp;
    while (1)
    {
        if (x > y)
        {
            temp = x;
            x = y;
            y = temp;
        }
        if (y > z)
        {
            temp = y;
            y = z;
            z = temp;
        }
        if (x > z)
        {
            temp = x;
            x = z;
            z = temp;
        }
        if (x < y && y < z && x < z)
            break;
    }
}

void sort2(int *x, int *y, int *z)
{
    int temp;
    while (1)
    {
        if (*x > *y)
        {
            temp = *x;
            *x = *y;
            *y = temp;
        }
        if (*y > *z)
        {
            temp = *y;
            *y = *z;
            *z = temp;
        }
        if (*x > *z)
        {
            temp = *x;
            *x = *z;
            *z = temp;
        }
        if (*x < *y && *y < *z && *x < *z)
            break;
    }
}

运行结果:



@ Mayuko

原文地址:https://www.cnblogs.com/mayuko/p/4567577.html