2014-01-26 24 views
0

我只是一個初學者,嘗試了一些代碼,我的老師教我們使用和教科書的東西。當「else」被觸發時,爲什麼循環會自行循環?這是因爲所謂的內存分配?

該程序旨在讓用戶輸入他們的名字並輸入密碼,系統要求他們放下。

有人可以向我解釋爲什麼當觸發else時,這個循環爲什麼會無限循環?

此外,cin.ignore對char名稱的內存做了什麼?爲什麼80比20好?

AND,爲什麼隨機數不是隨機的?每次運行它時,數字都是一樣的。

非常感謝大家!

#include <iostream> 
#include <cstdlib> 
using namespace std; 

int main() 
{ 
char name[20]; 
int pwd, rand1, rand2; 
for (int i=0;i<1; i++) 
    { 

    cout<<"Name:    "; 
    cin.get(name, 20); 
    cin.ignore(80, '\n'); 
    cout<<endl; 

     srand(rand() % 1000); 
     rand1 = (rand() % 21); 
     rand2 = (rand()%6); 
     cout<<"Password: "<<rand1<<"*"<<rand2<<"= "; 
     cin>>pwd; 

     if(pwd == rand1*rand2) 
     { 
      cout<<endl<<"Welcome to our main page, "<<name<<"."<<endl; 
     } 

     else 
     { 
      cout<<"Wrong password, type again." <<endl; 
      i--; 
     } 

    } 
return 0; 
} 
+0

如何提出一個問題?並且'rand'是隨機的,取決於正確播種它,例如當前時間。閱讀文檔中的一個例子。 –

+0

如果我在幾個帖子中使用了幾個帖子,我覺得我會發送帖子區域。將它們放在一起會佔用較少的頭版空間。我在這裏是新的,並且...還不知道規則:D – user2714524

+1

通過調用'srand()'用rand()的種子爲'rand()'生成發電機有點類似於期望在你買了晚餐之前把它拿出來,你不覺得嗎?這個'srand()'屬於'main()'調用的*的頂部,並且具有適當的種子('time(NULL)'是常見的,這是一個值得考慮的事情)。 – WhozCraig

回答

0

首先對代碼進行格式化將有助於您更好地理解。 也避免使用命名空間標準,它的不好的做法,並與名稱混淆全球範圍。如果你不想每次都寫std :: cout,std :: cin等,請使用std :: xxxx。

重新格式化代碼:

#include <iostream> 
#include <cstdlib> 
using std::cin; 
using std::cout; 
using std::endl; 

int main() 
{ 
    char name[20]; 
    int pwd, rand1, rand2; 

    for (int i = 0; i < 1; i++) { 
     cout << "Name:    "; 
     cin.get(name, 20); 
     cin.ignore(); 
     cout << endl; 

     srand(rand() % 1000); 
     rand1 = (rand() % 21); 
     rand2 = (rand() % 6); 
     cout << "Password: " << rand1 << "*" << rand2 << "= "; 
     cin >> pwd; 
     cin.ignore(); 

     if(pwd == rand1*rand2) { 
      cout << endl << "Welcome to our main page, " << name << "." << endl; 
     } else { 
      cout << "Wrong password, type again." << endl; 
      i--; 
     } 
    } 

return 0; 
} 

其次,你可以在上面的代碼中看到的線cin.ignore();已在cin >> pwd後添加。在代碼獲取cin >>名稱之前,在輸入中保留'\ n',忽略'\ n',獲取cin >> pwd,在輸入中留下'\ n',循環讀取輸入爲'\ n' ',在輸入中留下另一個'\ n',首先'\ n'被ci.ignore()移除,其次'\ n'通過cin >> pwd讀取,等等。至少這是我的理解它。

+0

非常感謝你!這現在更有意義! – user2714524

+0

但是我怎樣才能讓每個生成的數字都不一樣? – user2714524

+0

@ user2714524按照我所說的做(現在兩次)。這個代碼可能是正確的輸出或跳過數據,但是在C/C++程序中正確地選擇庫RNG是完全不正確的。 – WhozCraig

-1

有人已經回答了第一個問題:因爲當你我 - ,在for循環不斷下降,然後increasing.,通過卡西姆
然後,如果你的輸入超過20較長,程序中的我可能會停止。所以你需要cin.ignore(80,'\ n')來忽略多餘的輸入。數字80只是一個很大的數字。您可以將其替換爲另一個號碼 - 只有足夠大時纔可以。
你應該隨時間使用srand。 srand(time(null))可能會有所幫助。

+0

'numeric_limits :: max()'更好... – Paranaix

+0

我不明白爲什麼我會讓循環繼續重複。我最後不會和i ++的for循環讓它工作嗎? – user2714524

相關問題