我目前正在练习C++中函数的一些问题,遇到了这个问题:-
编写一个带有函数的程序来交换2个给定整数变量的值
我写了以下代码:-
#include <iostream>
using namespace std;
void swap(int n1, int n2){
int org_n1=n1; //fixing original value of n1 before changing
n1=n2;
n2=org_n1;
return;
}
int main() {
int num1, num2;
cin>>num1>>num2;
cout<<"The original value of num1 is: "<<num1<<endl;
cout<<"The original value of num2 is: "<<num2<<endl;
cout<<endl;
swap(num1, num2);
cout<<"The new value of num1 is: "<<num1<<endl;
cout<<"The new value of num2 is: "<<num2<<endl;
return 0;
}
该代码应该打印交换后的num1和num2的新值,但它会继续打印它们的原始值。这里有什么错误?
您只是在交换函数内部的变量。函数只获取变量的副本。
void swap(int& n1, int& n2){
这些代码获取原始变量,而不是副本。
因为您传递的是值,所以复制整数在函数中交换,但不会更改实数。你可以使用void swap(int &n1, int &n2)
或者您应该使用指针通过引用传递。
您需要通过引用传递,以便在函数中所做的更改反映在原始变量中使用此void swap(int &n1, int &n2)
而不是void swap(int n1, int n2)