使用按引用调用交换数的循环顺序的 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() 中,由用户提供 3 个数字的值。然后,在交换这些值之前显示这些值。调用函数 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;
广告