介绍
在本实验中,我们将讨论如何使用 C++ 中的函数来交换两个数字。借助函数,有两种方法可以解决这个问题:
在本实验中,我们将讨论如何使用 C++ 中的函数来交换两个数字。借助函数,有两种方法可以解决这个问题:
首先,在你喜欢的代码编辑器中创建一个新的 C++ 文件。你需要在实验开始时提供代码文件的路径和名称。例如:~/project/main.cpp
。
touch ~/project/main.cpp
在传值调用(Call by Value)中,调用函数时会传递实际参数,而对形式参数的操作不会影响实际参数。以下是实现方法:
#include<iostream>
using namespace std;
void swap(int x,int y);
/*Swapping of Two Numbers in C++ Using Functions Call by Value*/
int main()
{
int a,b;
cout<<"Enter the Two Numbers to Swap in C++: ";
cin>>a>>b;
cout<<"\nAfter Swapping of Two Numbers:";
swap(a,b);
return 0;
}
void swap(int x,int y)
{
int z;
/*Extra veriable for storing the value of first or second variable*/
z = x;
/*Copying the first variable value to the tempriory variable*/
x = y;
/*Copying the second variable value to the first variable*/
y = z;
/*Copying the tempriory variable value to the second variable*/
cout<<" "<<x<<" "<<y;
}
要运行代码,请保存文件并打开终端,输入以下命令:
g++ main.cpp -o main && ./main
在传引用调用(Call by Reference)中,我们将实际参数的地址传递给形式参数,因此对形式参数的修改会反映在实际参数上。以下是实现方法:
#include<iostream>
using namespace std;
void swap(int *x,int *y);
/*Swapping of Two Numbers in C++ Using Functions Call by Reference*/
int main()
{
int a,b;
cout<<"Enter Two Numbers To Swap: ";
cin>>a>>b;
swap(&a,&b);
cout<<"\nAfter Swapping Two Numbers: ";
cout<<a<<" "<<b<<" \n";
return 0;
}
void swap(int *x,int *y)
{
int z;
z = *x;
/*Copying the first variable Address to the temporary variable*/
*x = *y;
/*Copying the second variable Address to the first variable*/
*y = z;
/*Copying the temporary variable Address to the second variable*/
}
要运行代码,请保存文件并打开终端,输入以下命令:
g++ main.cpp -o main && ./main
main.cpp
文件的完整代码以下是 main.cpp
文件的完整代码:
#include<iostream>
using namespace std;
void swap(int x,int y);
/*Swapping of Two Numbers in C++ Using Functions Call by Value*/
void swap(int *x,int *y);
/*Swapping of Two Numbers in C++ Using Functions Call by Reference*/
int main()
{
int a,b;
cout<<"Enter the first number: ";
cin>>a;
cout<<"Enter the second number: ";
cin>>b;
// Method 1: Call By Value
cout<<"\nSwapping of Two Numbers Using Call By Value\n";
swap(a,b);
// Method 2: Call By Reference
cout<<"\nSwapping of Two Numbers Using Call By Reference\n";
swap(&a,&b);
return 0;
}
void swap(int x,int y)
{
int z;
/*Extra veriable for storing the value of first or second variable*/
z = x;
/*Copying the first variable value to the tempriory variable*/
x = y;
/*Copying the second variable value to the first variable*/
y = z;
/*Copying the tempriory variable value to the second variable*/
cout<<" "<<x<<" "<<y;
}
void swap(int *x,int *y)
{
int z;
z = *x;
/*Copying the first variable Address to the temporary variable*/
*x = *y;
/*Copying the second variable Address to the first variable*/
*y = z;
/*Copying the temporary variable Address to the second variable*/
}
保存文件后,打开终端并输入以下命令以运行代码:
g++ main.cpp -o main && ./main
在本实验中,我们学习了如何在 C++ 编程语言中使用函数通过传值调用(Call by Value)和传引用调用(Call by Reference)方法来交换两个数字。