2017-04-15 67 views
-4
  1. 我遇到了一个随机生成的数字结果与用户输入不匹配的问题,它只输出第一条语句而不是落在其他位置,如果用户猜错了。随机生成的数字结果与用户输入不匹配

    #include <iostream> 
    #include <ctime> 
    #include <cstdlib> 
    #include <string> 
    
    using namespace std; 
    
    
    int main() 
    { 
    
        int bank = 10; 
        int heads = 0; 
        int tails = 1; 
        char response; 
        string headsTails; 
        int coinToss = rand() % 2; 
        srand(static_cast<int>(time(0))); 
    
    
        cout << "Welcome to the coin flip game. It cost a dollar to play. " << endl; 
        cout << "If you guess correctly you will win $2.00 dollars " << endl; 
        cout << "Do you want to play? (Y/N) " << endl; 
        cin >> response; 
    
    
        while (toupper(response) == 'Y') 
        { 
         cout << "Your bank is $" << bank << " dollars." << endl; 
         cout << "Enter head or tails (H/T)" << endl; 
         cin >> response; 
    
         coinToss = rand() % 2; 
         headsTails = coinToss ? "Heads" : "Tails"; 
    
         if (coinToss == heads || coinToss == tails) 
         { 
          cout << "Winner! The coin flip came up " << headsTails << endl; 
          cout << "Would you like to play again? (Y/N) " << endl; 
          cin >> response; 
          bank += 2; 
         } 
         else 
         { 
          cout << "Sorry, you lose. The coin flip came up " << headsTails << 
    endl; 
          cout << "Would you like to play again? (Y/N) " << endl; 
          cin >> response; 
          bank -= 1; 
         } 
    
        } 
        cout << "Thanks for playing! Your bank is " << bank << endl; 
        cout << "Please come again! " << endl; 
        return 0; 
    } 
    
+1

如果你想比较硬币的结果折腾到用户输入,你实际上应该这样做。你现在忽略用户输入。代码的作用并不神秘,你做到了。 – harold

回答

0
if (coinToss == heads || coinToss == tails) 

这个条件是错误的,它会始终为true,因为你coinToss为0或1自己设置。

您必须使用response变量你问用户,是这样的:

int guess = response == 'T' ? 1 : 0; // convert the user input to the same values used throughout the program. 
if(guess == coinToss) 
//won.. 
else 
//lost.. 
+0

谢谢!我知道这种情况有什么问题,我不知道我没有想到将结果与用户输入进行比较。 – Revved