简体   繁体   中英

How to call a C function that simply prints out a statement depending on the parameter

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

int guessGame(int guessed_num){
    int counter = 0;
    int random_num = 0;

 while(1)
    {
        counter++;
        if (guessed_num == random_num)
        {
            printf("Correct! That's the number.\n", counter);
            break;
        }

        if (guessed_num < random_num)
            printf("Too low. Guess again.\n");

        if (guessed_num > random_num)
            printf("Too high. Guess again.\n");

    }

}

int main(){

int guessed_num = 0;


srand(time(NULL));
int random_num = rand() % 50 + 1;

printf("I have a number between 1-50.\n");
printf("Can you guess what it is?\n");
printf("Enter your initial guess.\n");

        scanf("%d", &guessed_num);
        printf("%d\n" ,guessGame(guessed_num));


return 0;
}

So i have to make a guessing game where the user has to correctly guess a randomly created integer. The thing is, I have to use a function to run the actual guessing game. I'm stuck because I don't know how to properly call my function. I know for a fact my printf statement in my main function is not the proper way to do it.

Since you just want to print out the guess status (too high, too low, etc.) depending upon the single parameter the user enters, it is not necessary for you to use the while loop within your function. The below code will help:

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

int random_num;
void guessGame(int guessed_num){


if (guessed_num == random_num)
    printf("Correct! That's the number.\n", guessed_num);
else
    if (guessed_num < random_num)
        printf("Too low. Guess again.\n");
    else
        printf("Too high. Guess again.\n");
}

int main(){

int guessed_num = 0;
srand(time(NULL));
random_num = rand() % 50 + 1;

printf("I have a number between 1-50.\n");
printf("Can you guess what it is?\n");
while(1){
printf("Enter your initial guess.\n");

    scanf("%d", &guessed_num);
    guessGame(guessed_num);
}

return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM