我在看java中的方法是,调用Swap(int x,int y)方法进行值交换,可结果x,y的值没有被调换,那为什么其他时候,我们在调用方法的时候却能达到我们的目的,比如说我们在调用max(x,y)方法的时候,却能得到我们需要的结果?
我特意用C++验证了一下,发现调用swap(x,y)也没能把值交换
#include<iostream.h>
void swap(int x,int y);
void main()
{
int num1=1;
int num2=2;
cout<<"Before invoking the swap method ,num1 is: "<<num1<<"\n"<<"and num2 is: "<<num2<<endl;
swap(num1,num2);
cout<<"After invoking the swap method ,num1 is: "<<num1<<"\n"<<"and num2 is: "<<num2<<endl;
}
void swap(int n1,int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
}
同样是方法,为什么有的能达到我们的目的,有的却不能?
我特意用C++验证了一下,发现调用swap(x,y)也没能把值交换
#include<iostream.h>
void swap(int x,int y);
void main()
{
int num1=1;
int num2=2;
cout<<"Before invoking the swap method ,num1 is: "<<num1<<"\n"<<"and num2 is: "<<num2<<endl;
swap(num1,num2);
cout<<"After invoking the swap method ,num1 is: "<<num1<<"\n"<<"and num2 is: "<<num2<<endl;
}
void swap(int n1,int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
}
同样是方法,为什么有的能达到我们的目的,有的却不能?
{
public int swap(int x,int y)
{
int temp;
if(x>y)
temp = x;
else
temp = y;
return temp;
} public static void main(String[] args)
{
int num1 = 2541;
int num2 = 3396;
int c;
c = swap(num1,num2);
System.out.println("num1="+num1);
System.out.println("num2="+num2);
System.out.println("c="+c);
}
}你看这个程序就知道了,c里面就可以得到被调用函数里面换了的值,因为c里面是被调用函数里面的返回值