作者johnjohnlin (嗯?)
看板EE_DSnP
標題[請益] gcd 的問題
時間Thu Nov 6 20:06:30 2008
先附程式碼
int main(){
cout<<"enter two intergers"<<endl;
int a ; int b;
cin>>a;
cin>>b;
cout<< "the GCD of "<<a<<" and "<<b <<"= "<<
gcd(a,b)<<endl;
system("pause");
}
int gcd(int x,int y){
if(x>y){int c ; c=x;x=y; y=c;}
else{}
if(y%x==0){
cout<< "the GCD is "<<x <<endl; return x;}
else{gcd(y%x,x);}
}
輸出結果
1.正常情形
enter two intergers
13
169
the GCD is 13
the GCD of 13 and 169= 13
請按任意鍵繼續 . . .
2.不知名的bug
enter two intergers
12
8
the GCD is 4
the GCD of 12 and 8= 2088809675
請按任意鍵繼續 . . .
請問 為什麼 一個是 return x; 再cout
一個是直接cout x
輸出的會不一樣?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.241.150
1F:→ ilway25:沒有問題耶.. 11/06 20:24
2F:推 ric2k1:我想你的 else return gcd(...) 比較好. 11/06 20:52
3F:推 stimim:我比較好奇的是,gcd(0,0)會發生甚麼事? 11/06 22:46
4F:推 ric2k1:關於 gcd 可以參考 #584 #585 11/06 22:53
5F:→ johnjohnlin:還是不行...好像把int 改成 void 不加 return 就行了 11/07 00:00
6F:推 ric2k1:不會吧, 我是說改成: else{ return gcd(y%x,x); } 11/07 00:25
7F:→ ric2k1:應該就可以了... 11/07 00:25
8F:→ ric2k1:不過你 gcd(0,0) 會 crash 哦! 11/07 00:26