日期:2014-05-20  浏览次数:20635 次

while((n%m)!=0) ,while(n%m!=0) ,while((n%m))有什么区别 ??
求最大公约数的一个方法 其中这几句 while((n%m)!=0) ,while(n%m!=0) ,while((n%m))有什么区别  
class Count1{
public static int count(int n,int m)throws Exception{
int i;
int j;
n=n>m?n:m;
while((n%m)!=0){ //这是正确的写法 可是如果我换成
//while(n%m!=0) 不提示错误 可算法结果错误
// while((n%m))提示出错 为什么呢 在C语言上都是允许这种写法的
//我希望 大虾知道的 可以和我说下 这三种用法 在JAVA中使用的区别 
//本人之前都是学C语言的 所以对JAVA有很多不懂 希望大家帮帮忙。。谢谢了 感激不尽
i=m;
m=n%m;
n=i;
}
return m;
}
}



谢谢各位~~~
另外补上完全代码 可以调试一下~~~
import java.io.*;
import java.util.Scanner;

class Count{
public static int count1(int n,int m)throws Exception{
int i;
int j;
n=n>m?n:m;
while((n%m)!=0){
i=m;
m=n%m;
n=i;
}
return m;
}

public static int count2(int n,int m, int k )throws Exception{
return n*m/k;
}
}

class Apply{

public void apply() throws Exception{
BufferedReader buffered=new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入n和m:");
int n=Integer.parseInt(buffered.readLine());
int m=Integer.parseInt(buffered.readLine());
System.out.println(n+"和"+m+"的最大公约数为:"+Count.count1(n,m)+"\t最小公倍数为:"+Count.count2(n,m,Count.count1(n,m)));
}
}

public class gongyueshu{
public static void main(String args[]){
try{
new Apply().apply();
}


catch(Exception e){

System.out.println("异常"+e);
}
}
}

------解决方案--------------------
while((n%m)!=0)
while(n%m!=0) 
这2句差距在优先级上,
第一句先n%m得到一个int tmp,然后tmp!=0返回true/false
第二句先m!=0得到boolean true/false;然后n%true不会报错,这里true自动转换为1,但是n%false会报错,报除数不能为0的错,这里false自动转换为0,这是java的强制转换的机制
while((n%m)) 先n%m得到一个int tmp,然后while(tmp)就会报错,这是因为while之后只能加boolean,不能加数字
------解决方案--------------------
首先声明 本人新手 
如有错误 概不负责
public static int count1(int n,int m)throws Exception{
 int i;
 int j;
 n=n>m?n:m;
 while((n%m)!=0){
 i=m;
 m=n%m;
 n=i;
 }
 return m; 
}
 你的这个求最大公约数的求法本来就错了

 while((n%m)!=0) while(n%m!=0) 因为%运算符的优先级高于 !=所以,两者没有什么区别!要有区别的话
就前者的可阅读性 比 后者的好
// while((n%m))提示出错 为什么呢
 while(必须是 boolean)而n%m 是int 在java中 int不能转换成 boolean