使用按引用呼叫交換數的迴圈順序的 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;
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP