C ++程序使用引用调用按循环顺序交换数字
cyclicSwapping()
通过按引用调用将三个数字传递给函数,可以按循环顺序交换三个数字。此函数以循环方式交换数字。
使用引用调用以循环顺序交换数字的程序如下:
示例
#include<iostream> using namespace std; void cyclicSwapping(int *x, int *y, int *z) { int temp; temp = *y; *y = *x; *x = *z; *z = temp; } int main() { int x, y, z; cout << "Enter the values of 3 numbers: "<<endl; cin >> x >> y >> z; cout << "Number values before cyclic swapping..." << endl; cout << "x = "<< x <<endl; cout << "y = "<< y <<endl; cout << "z = "<< z <<endl; cyclicSwapping(&x, &y, &z); cout << "Number values after cyclic swapping..." << endl; cout << "x = "<< x <<endl; cout << "y = "<< y <<endl; cout << "z = "<< z <<endl; return 0; }
输出结果
上面程序的输出如下-
Enter the values of 3 numbers: 2 5 7 Number values before cyclic swapping... x = 2 y = 5 z = 7 Number values after cyclic swapping... x = 7 y = 2 z = 5
在上面的程序中,该函数cyclicSwapping()
使用按引用调用按循环顺序交换三个数字。该函数使用变量temp来执行此操作。为此的代码片段如下-
void cyclicSwapping(int *x, int *y, int *z) { int temp; temp = *y; *y = *x; *x = *z; *z = temp; }
在该功能中main()
,这三个数字的值由用户提供。然后在交换它们之前显示这些值。cyclicSwapping()
调用该函数交换数字,然后在交换数字后显示值。这在下面给出-
cout << "Enter the values of 3 numbers: "<<endl; cin >> x >> y >> z; cout << "Number values before cyclic swapping..." << endl; cout << "x = "<< x <<endl; cout << "y = "<< y <<endl; cout << "z = "<< z <<endl; cyclicSwapping(&x, &y, &z); cout << "Number values after cyclic swapping..." << endl; cout << "x = "<< x <<endl; cout << "y = "<< y <<endl; cout << "z = "<< z <<endl;