0

I wanted to make a game where in which you get three turns to guess the selected number, from the computer. However it will never say well done even if you get the number right (already tested using printf statements) and the loop will also mess up by either continuing or running twice.

I've tried removing the break. I've put in printf statements to check if randomise and questions actually store the correct values and they do.

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

int questions() {

    int num;

    printf("Chose a number between one - ten: ");
    scanf("%d",&num);

    return num;

}

int randomise() {

    int roll;

    srand(time(NULL));

    roll = rand()%10 + 1;
    return roll;

}

int main() {

    int chosenNum, enteredNum, i;

    chosenNum = randomise();
    enteredNum = questions();

    for(i = 0; i < 10; i++) {
        if(chosenNum != enteredNum) {

            questions();
            break;

        }
        else if(chosenNum == enteredNum) {

            printf("WELL DONE !!!");

        }
    }

    return 0;
}

Zero errors and Zero warnings. and the outcome should be that you get greeted with well done.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
Ash
  • 15
  • 4

3 Answers3

1

There are two issues:

  1. You are using break which will not allow another attempt to input the number if first number is not matched, and
  2. the return value from questions() in the loop is not assigned to enteredNum (it means it will try old number second time).
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
ChauhanTs
  • 439
  • 3
  • 6
  • Thankyou for your feedback, I have taken it on board and it now works perfectly. Cheers – Ash Aug 18 '19 at 21:48
0

enteredNum is never set inside the loop. Thus, it's impossible for the if be false unless it is false the first time.

Fix your loop to something like this instead:

for(i = 0; i < 10; i++){
 if(chosenNum != enteredNum){

    enteredNum = questions();
    break;

   }
   else if(chosenNum == enteredNum){

      printf("WELL DONE !!!");

   }
}
0

This is the most recent update of the code, thanks for all your help guys. The feedback was great ! Heres the code:

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

int questions(){

int num;

printf("Chose a number between one - ten: ");
scanf("%d",&num);

return num;

}

int randomise() {

int roll;

srand(time(NULL));

roll = rand()%10 + 1;

return roll;

}

int main(){

int chosenNum, enteredNum, i;

int life = 3;

chosenNum = randomise();
enteredNum = questions();

for(i = 0; i < 2; i++){

enteredNum = questions();

 if((enteredNum != chosenNum) && life > 0){

    life -= 1;

    if(life == 1 ){

    printf("GAME OVER !!!\n");
    break;

      }

    }
    else if((chosenNum == enteredNum) && life > 0){

    printf("WELL DONE !!!\n");
    break;

   }

}

return 0;

}
Ash
  • 15
  • 4