2014-03-03 19 views
0

請仔細閱讀任務第一:http://codeabbey.com/index/task_view/neumanns-random-generator諾伊曼的隨機數發生器

我必須跟蹤迭代的次數,但我得到非常奇怪的結果。在任務之後的例子中,我們有數字0001和4100,並且它們應該在2次和4次迭代之後循環。但我的結果是1,4或者如果我改變計數器的地方2或5,但從來沒有2和4。這裏是我的代碼:

#include <iostream> 
#include <math.h> 
#include <stdlib.h> 
#include <vector> 
#include <algorithm> 

using namespace std; 

int main() 
{ 
    int n; 
    int value; 
    int counter; 
    int result; 
    int setvalue = 1; // use to exit the loop if setvalue == 0; 
    cin >> n; 
    vector<int> new_results(0); // use to store all the results from iterations 
    vector<int> results_vec(0); // use to store the number of iterations for each number 

    for (int i = 0; i < n ; i++) 
    { 

     cin >> value; 
     while(setvalue == 1) 
     { 
      value = value*value; 

      value = (value % 1000000)/100; 

      if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end()) 
      { 
       results_vec.push_back(value); 
      } 
      else 
      { 
       counter = results_vec.size(); 
       new_results.push_back(counter); 
       setvalue = 0; 
      } 

     } 
     results_vec.clear(); 


    } 
    for (int i = 0; i < new_results.size() ; i++) 
    { 
     cout << new_results[i] << " "; 
    } 

} 
+0

如果您以0001和4100開頭,會生成哪些中間數字? – tgmath

+0

對於0001我得到(0,0) 對於4100我得到(8100,6100,2100,4100) – Vallerious

+0

在開始while循環之前你不應該將初始種子值放入'results_vec'嗎? – pjs

回答

2

進出字符串你有辦法真的非常難看且非常昂貴的計算。

使用

(value % 1000000)/100;

,而不是提取中間四位數字。這工作通過(1)取模數刪除前兩位數然後(2)刪除最後兩個整數除法。

因爲它非常簡單,我懷疑它也會修復你的錯誤。

+0

int也是9999^2太小,你必須使用long。 – tgmath

+0

@tgmath 9999^2大約爲99,980,001,遠低於2,147,483,647(2^31 -1),所以在通常的平臺上(即int> = 32位),這就足夠了。當然,標準並不保證int至少有32位:保證的下限是16位。 – stefan

+0

哇,謝謝!沒有必要使用該字符串轉換後,所有:) 但問題仍然存在 - 當if語句發現該數字已在向量中,這意味着我們來到一個循環它不添加最後一個數字迭代並跳轉到將其添加到new_results向量的else。 – Vallerious

0

這裏是正確的代碼,謝謝你的幫助。

#include <iostream> 
#include <math.h> 
#include <stdlib.h> 
#include <vector> 
#include <algorithm> 

using namespace std; 

int main() 
{ 
    int n; 
    int value; 
    int counter; 
    int result; 
    cin >> n; 
    vector<int> new_results(0); // use to store all the results from iterations 
    vector<int> results_vec(0); // use to store the number of iterations for each number 

    for (int i = 0; i < n ; i++) 
    { 

     cin >> value; 
     results_vec.push_back(value); 
     while(true) 
     { 
      value = value*value; 

      value = (value % 1000000)/100; 

      if(find(results_vec.begin(), results_vec.end(), value) == results_vec.end()) 
      { 
       results_vec.push_back(value); 
      } 
      else 
      { 
       counter = results_vec.size(); 
       new_results.push_back(counter); 
       break; 
      } 

     } 
     results_vec.clear(); 


    } 
    for (int i = 0; i < new_results.size() ; i++) 
    { 
     cout << new_results[i] << " "; 
    } 

}