Switch语句中的变量更改但未反映在其余代码中

时间:2017-09-18 01:43:04

标签: c++

我是C ++的新手,我正在写一篇Rock,Paper&剪刀游戏为我的C ++类。在算法中,我被告知要执行以下操作:

  

使用switch语句,在computerChoice中将随机数(1-3)更改为“R”,“P”和“S”

现在,我已经这样做了,computerChoice语句中的变量switch未在if语句中使用。

我在这里做错了什么?

这是我的代码:

/*
This program is a game of rock, paper and scissors.
*/

#include<iostream> // required for cin, cout
#include<ctime>     // required for time
#include<cstdlib>  // required for srand(), rand()

using namespace std; 

int main() // main function

{

        srand(time(0)); // seed (number will appear once)


        // declaring variables as characters
        char userChoice;

        // prompt the user toar  enter R for rock, S for scissors or P for paper
        cout << "Enter R for rock, S for scissors or P for paper." << endl;
        cin >> userChoice;

        int computerChoice = rand()%3; // to generate a number between 0 and 2 

        cout << "The computer chose the number " << computerChoice << endl;

        // convert 0 to R, 1 to S and 2 to P
        switch(computerChoice) 
        {

            case 0:
                computerChoice = 'R'; // convert 0 to Rock
                cout << "Computer chose Rock. " << endl; // print rock as computer's choice
                break;

            case 1:
                computerChoice = 'S'; // convert 1 to Scissors
                cout << "Computer chose Scissors. " << endl; // print scissors as computer's choice
                break;

            case 2:
                computerChoice = 'P'; // convert 2 to Paper
                cout << "Computer chose Paper. " << endl; // print paper as computer 's choice
                break;
        }


        // Determine the victor
        if (computerChoice == userChoice) { // Computer's choice is equal to User's Choice
            cout << "It's a tie. " << endl;
        }

        else if (computerChoice == 'R') { // Computer chose Rock

            if (userChoice == 'P') {// User chose Paper
            cout << "User wins - paper covers rock" << endl;
            }
            else {// User chose Scissors
            cout << "Computer wins - rock crushes scissors" << endl;
            }
        }
        else if (computerChoice == 'S') { // Computer chose Scissors

            if (userChoice == 'R') { // User chose Rock
            cout << "Computer wins - rock crushes scissors" << endl;
            }
            else { // User chose Paper
            cout << "Computer wins - scissors cuts paper" << endl;
            }
        }

        else //computer chose Paper
            {

            if (userChoice == 'R') { // User chose Rock
            cout << "Computer wins - paper covers rock" << endl;
            }
            else { // User chose Scissors
            cout << "User wins - scissors cuts paper" << endl;
            }
        }   

    return (0); //Stop program
} // Close Main function

0 个答案:

没有答案
相关问题