-4
我遇到了一个随机生成的数字结果与用户输入不匹配的问题,它只输出第一条语句而不是落在其他位置,如果用户猜错了。随机生成的数字结果与用户输入不匹配
#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; }
如果你想比较硬币的结果折腾到用户输入,你实际上应该这样做。你现在忽略用户输入。代码的作用并不神秘,你做到了。 – harold