2016-02-22 108 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"); 
    } 
}