Моя функция пока l oop не работает из-за этой функции? - PullRequest
0 голосов
/ 24 апреля 2020

Я создаю программу, в которой пользователю предлагается угадать число 1-100, о котором думает компьютер.

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

Чтобы решить эту проблему, я попытался использовать do while l oop & char repeat;. L oop тянется от начала программы до самого конца, хотя и безуспешно. Кто-нибудь знает, что я делаю не так? Это из-за функции talfunktion, что l oop не пройдет?

Код:

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

int talfunktion (int tal, int guess, int tries, char repeat);

int main () {

do {
    srand(time(NULL));
    int tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of 
    int guess; //guess is the guessed value of the user
    int tries = 0; // amount of tries it took until getting correct
    char repeat;


    printf("Psst, the right number is: %d \n", tal); // remove later, not relevant to uppg.

    printf("Im thinking of a number between 1 and 100, guess which!");
    printf("\nEnter: ");
    scanf("%d", &guess);
    guess = talfunktion(tal, guess, tries, repeat);

    getchar();
    getchar();
    return 0;

    }

    int talfunktion(int tal, int guess, int tries, char repeat) {
        do {
            if (guess < tal) {
                tries++;
                printf("\nYour guess is too low, try again!");
                printf("\nEnter: ");
                scanf("%d", &guess);
            }
            else if (guess > tal) {
                tries++;
                printf("\nYour guess is too high, try again!");
                printf("\nEnter: ");
                scanf("%d", &guess);
            }
        } while (guess > tal || guess < tal);

        if (guess == tal) {
            printf("\nCongratulations, that is correct!");
            tries++;
            printf("\nYou made %d attempt(s)", tries);
            printf("\nPlay Again? (y/n)");
            scanf("%c", &repeat);
    }
} while (repeat == 'y' || repeat == 'Y');


}



Ответы [ 2 ]

0 голосов
/ 24 апреля 2020

Это одно из возможных решений

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

void talfunktion(int tal, int guess, int* tries)
{
            if (guess < tal)
            {
                (*tries)++;
                printf("\nYour guess is too low, try again!");
            }
            else if (guess > tal)
            {
                (*tries)++;
                printf("\nYour guess is too high, try again!");
            }
            else if (guess == tal)
            {
                (*tries)++;
                printf("\nCongratulations, that is correct!");
                printf("\nYou made %d attempt(s)", *tries);
            }
}

int main (void)
{
    int tal; //tal is the correct value that the code is thinking of
    int guess; //guess is the guessed value of the user
    int tries = 0; // amount of tries it took until getting correct
    char playAgain;

    do {
            srand(time(NULL));
            tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
            printf("\nIm thinking of a number between 1 and 100, guess which!");
            printf("\nEnter: ");
            scanf("%d", &guess);
            talfunktion(tal, guess, &tries);

            printf("\nPsst, the right number is: %d", tal); // remove later, not relevant to uppg.
            getchar(); //to halt the code for taking the input

            if(guess == tal)
            {
                tries = 0;
                printf("\nPlay Again? (y/n)\n");
                scanf("%c", &playAgain);
            }

    } while (playAgain != 'n');

return 0;
}
0 голосов
/ 24 апреля 2020

В комментариях упоминаются несколько вещей, описывающих проблемы, на которые следует обратить внимание:

  • Не определяйте функцию внутри другой функции
  • будьте осторожны в том месте, куда вы помещаете return операторы
  • при использовании символьного тестирования используйте тип char для переменной
  • и попробуйте упростить свои логические сравнения. (например, guess > tal || guess < tal - это то же самое, что и guess != tal)
  • . Убедитесь, что автоматические c переменные размещены так, что они видны при использовании.
  • Поместите пробел в спецификатор формата: " %c" для scanf(), чтобы использовать символ новой строки. (вместо чрезмерного использования getchar())

Вот упрощенная версия вашего кода с измененными функциями main и talfunktion ...

char talfunktion(int tal);

int main (void) {
     int tal=0;//remove from inside {...} to make it visible to rest of function
     char repeat = 'n';

     srand(time(NULL));
     tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of 

    do {

            repeat = talfunktion(tal);

        }while((tolower(repeat) == 'y'));

        return 0;
}

char talfunktion(int tal)//do all relevant work in function and return 
{                        //only what is necessary
     int guess = 0;
     char repeat = 'n';


    printf("Im thinking of a number between 1 and 100, guess which!");
    printf("\nEnter a number from 1 to 100: ");
    scanf("%d", &guess);
    if((guess < 1) || (guess > 100))
    {
        printf("Entered out of bounds guess...\n");
    }
    else if (guess != tal)
    {
        if(guess < tal) printf("guess too small\n");
        else printf("guess too large\n");
        printf("Try  again? <'n' or 'y'>\n");
        scanf(" %c", &repeat);//space in format specifier to consume newline character
        if(tolower(repeat) != 'y') return 'n';//tolower() allows both upper and lower case
    }
    else
    {
        printf("Congratulations: You guessed right.\n");
        printf("Play again? <'n' or 'y'>\n");
        scanf(" %c", &repeat);
    }
    return repeat;
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...