Skip to content

Latest commit

 

History

History
72 lines (51 loc) · 1.78 KB

File metadata and controls

72 lines (51 loc) · 1.78 KB

C++ 程序:使用引用调用以循环顺序交换数字

原文: https://www.programiz.com/cpp-programming/examples/swapping-cyclic-order

该程序从用户那里获取三个整数,并使用指针以循环顺序交换它们。

要理解此示例,您应该了解以下 C++ 编程主题:


用户输入的三个变量分别存储在变量abc中。

然后,将这些变量传递给函数cyclicSwap()。 而不传递实际变量,而是传递这些变量的地址。

当这些变量在cyclicSwap()函数中以循环顺序交换时,在main函数中的变量abc也将自动交换。

示例:使用按引用调用交换元素的程序

#include<iostream>
using namespace std;

void cyclicSwap(int *a, int *b, int *c);

int main()
{
    int a, b, c;

    cout << "Enter value of a, b and c respectively: ";
    cin >> a >> b >> c;

    cout << "Value before swapping: " << endl;
    cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl;

    cyclicSwap(&a, &b, &c);

    cout << "Value after swapping numbers in cycle: " << endl;
    cout << "a, b and c respectively are: " << a << ", " << b << ", " << c << endl;

    return 0;
}

void cyclicSwap(int *a, int *b, int *c)
{
    int temp;
    temp = *b;
    *b = *a;
    *a = *c;
    *c = temp;
}

输出

Enter value of a, b and c respectively: 1
2
3
Value before swapping: 
a=1
b=2
c=3
Value after swapping numbers in cycle:
a=3
b=1
c=2

注意,我们没有从cyclicSwap()函数返回任何值。