2016-12-11 2 views
-1

Попытка выяснить, как я могу заставить компьютер угадать 9-значное двоичное число 7 раз и когда правильно выводить, что введенный номер верен.C++ Устранение ошибки в компьютере

Также, если кто-либо знает, как подсчитать количество 0 и 1 в двоичном числе, которое было бы оценено, я пробовал читать на std :: count(), но не понял его, поскольку я очень новичок в C++.

Cheers.

void breakyourcode() 
    { 
     cout << "You have picked break your code" << endl; 
     string guess; 
     int tries = 7; 
     srand(time(NULL)); 
     int index = rand() % 512; 
     string cGuess = index2code(index); 
     cout << cGuess << endl; 

     cout << "Enter a number: "; 
     cin >> guess; 

     do { 
      cout << "\nComputer's guess: " << endl; 
      cout << cGuess; 
      ++tries; 

      if (guess == cGuess) { 
       cout << "Yeeha! I won!" << endl; 
       system("PAUSE"); 
       break; 
      } 
      cGuess = rand() % 512; 

     } while (guess != cGuess); 

     return; 
    } 

ответ

0

Непонятно, что вы имеете в виду - двоичное число представляет собой просто представление числа. Любое старое рациональное число может быть выражено как двоичное число (компьютеры не будут работать иначе!)

Вы хотите вывести номер в двоичном формате, например. 00000101 вместо 5?

Если это так, незавершенная программа покажет вам, как (взято из here):

#include <bitset> 
#include <iostream> 

int main() { 
    int x = 5; 
    std::cout << std::bitset<8>(x) << std::endl; 
} 
0

В моей интерпретации вашего вопроса я предположил, что вы хотите беззнаковое число - хотя я предполагаю, что это должно работать с целыми числами так же, как и.

Другое предположение, что я хочу сказать, что вы хотите, чтобы пользователь вводил числа как единицы и нули, которые помещаются в строку, а затем преобразуются в целое число unsigned по функции convertBinaryNumberStringToInt.

Здесь приведен код, указывающий, как вы могли бы это сделать, включая функцию howManyOnes, специально предназначенную для подсчета количества ее в двоичной форме вашего номера.

#include <iostream> 
#include <string> 

// For CHAR_BIT 
#include <climits> 

// For std::reverse, but you could 
// write your own string reverse function 
#include <algorithm> 

unsigned convertBinaryNumberStringToInt(const std::string& stringNumber) 
{ 
    unsigned outputNumber = 0; 

    // Using a reversed string allows us to insert ones in the 
    // number's binary form from right to left while still using 
    // a range-based for loop with not much tinkering 
    std::string reversedStrNum = stringNumber; 
    std::reverse(reversedStrNum.begin(), reversedStrNum.end()); 


    unsigned i = 1; 

    // i starts as 00000000000000000000000000000001 (binary, assuming 32 bits integer) 
    // On each iteration of the for loop, the 1 is shifted left and, 
    // if the current character is '1', the value 1 is copied into 
    // its corresponding current position in outputNumber 
    for(char c : reversedStrNum) 
    { 
     if(c == '1') 
     { 
      // The bitwise-or operation copies the 1 in i to 
      // its corresponding position in outputNumber 
      outputNumber = outputNumber | i; 

     } 
     // Shift i's 1 to the left by one position 
     i = i << 1; 
     // You could also do i *= 2, but we're specifically shifting 
     // bits, so the bitshift seems more "semantic" 
    } 

    return outputNumber; 
} 

bool isStringCorrect(std::string& userString, size_t maxSize) 
{ 
    if(userString.size() > 9) 
     return false; 

    for(char c : userString) 
     if(c != '1' && c != '0') 
      return false; 

    return true; 
} 

unsigned computerGuess(unsigned highBound) 
{ 
    return rand() % highBound; 
} 

unsigned howManyOnes(unsigned number) 
{ 
    unsigned count = 0; 
    unsigned shifter = 1; 

    // For each bit: sizeof(unsigned) is the size in bytes 
    // of an unsigned, CHAR_BIT is the bit length of a char or byte 
    // So we loop through each bit position. 
    for(unsigned i = 0; i < CHAR_BIT * sizeof(unsigned); i++) 
    { 
     // What we do is we test our number against the shifter 
     // for each bit position. If a bitwise-and between both 
     // is non-zero, it means number has 1 in that position, 
     // so we increase the "one" count. 
     if((number & shifter) != 0) 
      ++count; 

     // Either way, we left-shift the one in shifter afterwards 
     shifter = shifter << 1; 
    } 

    return count; 
} 

int main() 
{ 
    std::string userChoiceNumberString; 
    std::cout << "Enter a number: "; 
    std::cin >> userChoiceNumberString; 

    if(!isStringCorrect(userChoiceNumberString, 9)) 
    { 
     std::cout << "Entered string is incorrect" << std::endl; 
     return -1; 
    } 

    unsigned userChoiceNumber = convertBinaryNumberStringToInt(userChoiceNumberString); 

    std::cout << "Your number has " << howManyOnes(userChoiceNumber) << " ones in binary." << std::endl; 

    int attempts = 7; 
    while(attempts > 0) 
    { 
     if(computerGuess(512) == userChoiceNumber) 
     { 
      std::cout << "Yeeha! I won!" << std::endl; 
      attempts = 0; 
     } 
     else 
     { 
      std::cout << "Hmmm... guessed wrong..." << std::endl; 
      --attempts; 
     } 
    } 

    return 0; 
} 
Смежные вопросы