2016-02-22 109 views
-1

感謝您幫助我們,我一直在嘗試做密碼猜測匹配,但我有一些問題。問題是例如我的隨機密碼生成是1624,然後當輸入時問我輸入猜測密碼我輸入1325. 因此,輸出是:OXOX。 O表示正確,X表示不正確密碼猜測遊戲

但是,如何使用if語句來指定想法。此刻,我從生成密碼存儲每個位置,並將猜測密碼存儲到數組中。

這是我的想法:

if (x[0] == y[0] && x[1] == y[1] && x[2] == y[2] && x[3] == y[3]){ 
       cout << " OOOO" << endl; 
    } 

*****更正:**

的問題有,如果使用的是X [I] ==值Y [i]如果我去i = 1?怎麼還會比較位置0,1,2,3?我需要單獨匹配每個角色!現在如果我= 0我只會比較0,其餘的會被忽略!這我的意思:

生成的密碼:1234

INT I = 0; x = 0; 猜輸入:1845 輸出:OXXX

int i = 1; x = 1; 猜輸入:1200 輸出:OOXX

int i = 2; x = 2; 猜測輸入:0230 輸出X00X

這怎麼我的代碼看起來現在

void randomClass() { 
     std::generate_n(std::back_inserter(s), 10, 
         []() { static char c = '0'; return c++; }); 
     // s is now "" 

     std::mt19937 g(std::random_device{}()); 

     // if 0 can't be the first digit 
     std::uniform_int_distribution<size_t> dist(1, 9); 
     std::swap(s[0], s[dist(g)]); 

     // shuffle the remaining range 
     std::shuffle(s.begin() + 1, s.end(), g); // non-deprecated version 

     // convert only first four 
     x = std::stoul(s.substr(0, 4)); 
     std::cout<<x << std::endl; 

     //Store array 
     y[0] = x/1000; 
     y[1] = x/100%10; 
     y[2] = x /10%10; 
     y[3] = x %10; 




     } 

    void guess (string b) { 
     int x[4]; 

     for (int i =0; i < 4; i++) { 
     cout << "Make a guess:" << endl; 
     getline(cin,b); 
     int u = atoi(b.c_str()); 
     x[0] = u/1000; 
     x[1] = u/100%10; 
     x[2] = u /10%10; 
     x[3] = u %10; 




     } 

    } 
}; 

回答

0

而不是你的所有組合的...

if (x[0] == y[0] && x[1] == y[1] && x[2] == y[2] && x[3] == y[3]){ 
    cout << " OOOO" << endl; 
} 

...只是處理一個字符一段時間...

for (int i = 0; i < 4; ++i) 
    cout << (x[i] == y[i] ? 'O' : 'X'); 
cout << '\n'; 
0

將號碼保留爲人物特徵。然後可以使用數組索引訪問該數字。

比較容易比較guess[2]比分開然後用模取出數字。

0

希望這可以幫助你

#include <iostream> 
#include <math.h> 

int main() 
{ 
    // get input from user 
    std::string input; 
    std::cin>>input; 

    // set password 
    std::string password = "1234"; 

    // find size of lowest element string 
    int size = fmin(input.size(),password.size()); 

    // loop through all elements 
    for(int i=0;i<size;i++) 
    { 
     // if current element of input is equal to current element of password, print 'x', else print '0' 
     std::cout<<(input[i]==password[i]?"X":"0"); 
    } 
}