English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

用輾轉相除法求最大公因數
要有遞迴~以下不知道還有哪裡有錯誤~
請高手指導!!謝謝~
#include
void main()
{
int a,b;
cout<<"請輸入兩個數:"< cin>>a>>b;
{
if(a%b==0)
return b;
else
return (b,a%b);
}
}

2006-09-24 17:16:41 · 4 個解答 · 發問者 歐罵罵 4 in 電腦與網際網路 程式設計

4 個解答

#include
void main()
{
 int a,b;
 cout<<"請輸入兩個數:"<  cin>>a>>b;
 {     //<== 這裡..很怪
  if(a%b==0)
   return b;
  else
   return (b,a%b);
 }     //<==這裡也很怪
}  
===========分隔線===============
#include
using namespace std; // <=加這行才能使用 cin 和 cout

int gcd(int x, int y); //<= 用遞回要另外宣告一個function

int main(void)
{
  int a, b, c;
 cout << "請輸入兩個數字:" << endl;
  cin >> a >> b;
  c = gcd( a, b);
  cout << "輸出結果為:" << c << endl ;
  system("PAUSE");
  return 0;
}

int gcd (int x, int y)
{
 if( x % y == 0 )
  return y;
 else
  return gcd(y, (x%y) );
}
=========以上就是你寫的方式=========
不過這樣寫還有點小缺點
因為一開始你就判這行斷 if(a%b==0)
萬一user輸入b為0的話...成是就出錯了
所以如果在家一行 if( b != 0) 會更好!!!

2006-09-24 17:44:35 · answer #1 · answered by Rhyme09198679 2 · 0 0

直接用cin和cout方式有兩種:
#include
另一種是:
#include
using namespace std;

2006-09-25 06:31:10 · answer #2 · answered by Almond 6 · 0 0

#include
#include
int main()
{
int i,j,k;
printf("請輸入數字一:");
scanf("%d",&i);
printf("請輸入數字二:");
scanf("%d",&j);
for(k=i+1;k--;k<1)
{
if(i%k==0&&j%k==0)
{
printf("公因數=%d\n",k);
break;
}
}
return 0;
}

2006-09-25 09:20:27 補充:
『輾轉相除法』我不懂
不過你
if(a%b==0)
return b;
else
return (b,a%b);
這條件要求出最大公因數
只有在a=2b成立才做的到
公因數為其他數字時,你的程式也沒有其他的運算式能計算出來...
這應該才是你程式最大問題所在

2006-09-25 05:04:52 · answer #3 · answered by Xiao Lan 4 · 0 0

//Power by Microsoft Visual Studio 2005//可以使用 Dev-C++ 編譯此程式#include #include int main(int argc, char *argv[]){ //=====START=====// int fun_gcd(int num1st,int num2nd); int gcd_recursive(int num1st,int num2nd); int n1st,n2nd; printf("GCD and LCM\n"); printf("Input 1st number: "); scanf("%d",&n1st); printf("Input 2nd number: "); scanf("%d",&n2nd); //while 迴圈方法 printf("while...\n"); printf("GCD: %d\n",fun_gcd(n1st,n2nd)); printf("LCM: %d\n",n1st*n2nd/fun_gcd(n1st,n2nd)); //recursive 遞迴方法 printf("recursive...\n"); printf("GCD: %d\n",gcd_recursive(n1st,n2nd)); printf("LCM: %d\n",n1st*n2nd/gcd_recursive(n1st,n2nd)); //=====END=====// system("PAUSE"); return 0;}//mainint fun_gcd(int num1st,int num2nd){//while int num_3rd=EOF; while(num_3rd!=0){  num_3rd=num1st%num2nd;  num1st=num2nd;  num2nd=num_3rd; } return num1st;}int gcd_recursive(int num1st,int num2nd){//recursive if(num1st%num2nd==0){  return num2nd; }else{  return gcd_recursive(num2nd,num1st%num2nd); }}

2006-09-24 18:47:46 · answer #4 · answered by Big_John-tw 7 · 0 0

fedest.com, questions and answers