C++ 使用传引用循环顺序交换数字程序

要理解本示例,您应该了解以下 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() 函数返回任何值。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战