返回列表 發帖

三數求公因數

讓使用者依序輸入三個正整數, 電腦回應它們有那些公因數, 以及共有幾個公因數.
執行畫面如下:



本帖隱藏的內容需要回復才可以瀏覽

  1. #include<iostream>
  2. using namespace std;
  3. int main()
  4. {
  5.     int x,y,z,smaller;
  6.     int count=0;

  7.     cout<<"請依序輸入三個正整數:";
  8.     cin>>x>>y>>z;

  9.     if(x<y)
  10.     {
  11.         smaller=x;
  12.     }
  13.     else if(y<x)
  14.     {
  15.         smaller=y;
  16.     }
  17.     if(smaller<z)
  18.     {
  19.         smaller=z;
  20.     }
  21.     cout<<x<<y<<z<<"的公因數有:";
  22.     for(int i=1;i<=smaller;i++)
  23.     {
  24.         if(x%i==0 && y%i==0 && z%i==0)
  25.             cout<<i<<"\t";
  26.             count++;
  27.     }
  28.     cout<<endl<<"總共有"<<count<<"個!"<<endl;
  29. }
複製代碼

TOP

  1. #include<iostream>
  2. using namespace std;

  3. int main()
  4. {
  5.     re:
  6.     cout<<"請依序輸入三個正整數: ";
  7.     int x,y,z,sum=0;
  8.     cin>>x>>y>>z;
  9.     int smaller=x<y?x:y;
  10.     smaller=smaller<z?smaller:z;
  11.     cout<<x<<","<<y<<"與"<<z<<"的公因數有: ";
  12.     for(int i=1;i<=smaller;i++)
  13.     {
  14.         if(x%i==0 && y%i==0 && z%i==0)
  15.         {
  16.             cout<<i<<" ";
  17.             sum++;
  18.         }
  19.     }
  20.     cout<<endl<<"總共有"<<sum<<"個!"<<endl;
  21.     goto re;
  22. }
複製代碼

TOP

返回列表