在C++语言中,实现两数交换有两种途径:指针与引用。
下面是源代码:
#include
using namespace std;
void swap(int *i, int *j) //指针方法
{
int temp;
temp=*i;
*i=*j;
*j=temp;
}
void swap(int &i, int &j) //引用方法
{
int temp;
temp=i;
i=j;
j=temp;
}
void main(){
int m=1;
int n=2;
swap(&m, &n); //输出结果:m=2 n=1
cout<
cout<
swap(m, n); //输出结果:m=1 n=2
cout<
cout<
system("pause");
}
而在java中,这用普通类型是不能实现的:
public class test {
static void swap(int i, int j){
int temp;
temp=i;
i=j;
j=temp;
}
public static void main(String[] args){
int a=5;
int b=6;
swap(a,b);
System.out.println("this is a: "+a);
System.out.println("this is b: "+b); //this is a: 5 this is b: 6
}
}
这是因为java不能进行简单的直接赋值,且它不提供指针,这也是它与C++最大的区别。
那么到底能不能在java中实现值交换呢?
要说可以也行,就是写个类把数分装到类中去,对类进行操作。
不过我个人认为这样做太麻烦了,还不如勤快点自己多写几行代码呢~