ETH官方钱包

切換
舊版
前往
大廳
主題

【C++】輸入一數列,輸出數列中相同之值。

鍋貼企鵝 | 2012-07-07 19:56:10 | 巴幣 0 | 人氣 1418

這個題目想了很久,演算法是還好,用C++實現演算法花了一堆時間。
簡單說一下這程式的用途,假設輸入 1 1 1 2 3 那麼輸出便會是 1 。
就是找出相同的元素然後輸出就是了。

這程式相當笨重,因為實在是很懶得修,變數也設一堆,想到就寫上去,再加上沒使用函數,導致整個看起來很冗長。  XDD

未來有時間再來嘗試把它函數化吧。

以下提供程式碼。



#include<iostream>

using namespace std;

int main()
{
    int n;
    cout << "輸入數列長度:"<< endl;
    cin >> n;
    int A[n];
    bool temp[n];    
    for(int c=1;c<=n;c++)
            temp[c] = false;
    cout << "請輸入數列:" << endl;
    int i=1;
    while(i<=n)
    {     
         cin >> A[i];
         i++;
    }
    
    int a=1,b=1;
    while(a<=n)
    {
          while(b<=n)     
               {
                          if(b!=a)
                                  {
                                        if(A[a]==A[b])
                                                {      
                                                       temp[a] = true;
                                                       break;
                                                }       
                                        else
                                                b++;
                                  }
                          else
                                                b++;
               }
          a++;
          b=1;
    }
    int k=1,e=0;
    while(k<=n)  
        {
            if(temp[k]==true)
            {
                             e++;
                             k++;
            }
            else
                             k++;
        }
    int re[e];
    int g=1,f=1;
    while(g<=n)
    {
               if(temp[g]==true)
               {
                                re[f]=A[g];
                                f++;
                                g++;
               }
               else
                   g++;
    }
    for(int h=1;h<=e;h++)
    {
            for(int j=1;j<=e;j++)
                    {
                                 if(h!=j)
                                 {
                                         if(re[h]==re[j])
                                         {
                                                         re[h]=a;
                                                         break;
                                         }
                                 }
                    }
    }
    for(int l=1;l<=e;l++)
    {
            if(re[l]!=a)
                        cout << re[l]<<" ";
    }
    cout <<endl;
    system("pause");
    return 0;
}
    

相當繁雜是吧?
總之有空會嘗試把它修短的。  XDDD

最後再提供程式載點:sequence.exe


創作回應

OwO~??
它怎麼歪來歪去的xD
2012-07-18 23:33:08
鍋貼企鵝
這樣比較容易分段落。
2012-07-19 08:50:14

相關創作

更多創作