Я студент, застрявший на основной задаче практики «Рок, ножницы из бумаги» - PullRequest
0 голосов
/ 30 декабря 2018

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

Кто-нибудь видит, где я ошибся?

Для новичка, какие шагипринимать, если я не вижу ошибок или предупреждений в консоли?Как вы вообще знаете, с чего начать отладку?

Спасибо.

Моя последняя ошибка была в функции userChoice ().Я думаю, что моя проблема как-то связана со мной с помощью strcmp ().

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>


/* create a game of rock paper scissors*/

    char userInputString[9];
    int userInput;
    int computerInput;

/* Creates a random number between 1-3  the computer can
use as it's random choice for rock, paper or scissors.*/

 void computerChoice(){

    srand(time(NULL));
    int dice = rand()%3+1;

    if( dice = 1){

       int computerInput = 1;

    }else if( dice = 2){

        int computerInput = 2;

    }else if( dice = 3) {

        char computerInput = 3;

    }else{
        printf("Error! Something went wrong.");

    }

 }

/* Takes the rock, paper or scissors string typed by the user and converts it in to a number between 1-3
    that can be used to compare with the computers choice.*/


 void userChoice(){

     if(strcmp(userInputString,"rock")){

            userInput = 1;

     }else if(strcmp(userInputString,"paper")){

            userInput = 2;

     }else if(strcmp(userInputString,"scissors")){

            userInput = 3;
     }else{

        printf("Error! Something went wrong.\n");

     }

 }


/* compares the user and the computers choice then prints a winner to the console */

void compare(){

    switch(computerInput){

        case 1 : if(userInput = 1){
            printf("Computer picked Rock! It's a draw!\n");

        }else if(userInput = 2){
            printf("Computer picked Rock! You win!\n");

        }else if(userInput = 3){
            printf("Computer picked Rock! You lose!\n");

        }else{
            printf("Oops something went wrong.\n");

        }

        case 2 : if(userInput = 1){
            printf("Computer picked Paper! You lose!\n");

        }else if(userInput = 2){
            printf("Computer picked Paper! It's a draw!\n");

        }else if(userInput = 3){
            printf("Computer picked Paper! You win!\n");

        }else{
            printf("Oops something went wrong.\n");

        }case 3 : if(userInput = 1){
            printf("Computer picked scissors! You win!\n");

        }else if(userInput = 2){
            printf("Computer picked scissors! You lose!\n");

        }else if(userInput = 3){
            printf("Computer picked scissors! it's a draw!\n");

        }else{
            printf("Oops something went wrong.\n");

        }
    }
}

int main() {

        printf("Type rock, paper or scissors: \n");
        scanf("%s", &userInputString);

        computerChoice();
        userChoice();
        compare();

    return 0;
}

Я ожидаю, что в игре есть камень, ножницы, бумага с функциональными возможностями.

1 Ответ

0 голосов
/ 30 декабря 2018
if( dice = 1){

   int computerInput = 1;

}

Здесь (и в других местах) вы создаете новую локальную переменную, время жизни которой заканчивается, когда заканчивается блок.

Удалите декларатор int, чтобы оператор изменил существующую переменную области файла.

Кроме того, для сравнения используйте ==.= присваивает переменной новое значение, а это не то, что вам нужно.

if(strcmp(userInputString,"rock")){

        userInput = 1;

 }

strcmp() возвращает 0, если две строки совпадают.Поэтому добавьте == 0 к условию.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...