Home > other >  Trying to get computer to guess my number but get upper and lower limits to work
Trying to get computer to guess my number but get upper and lower limits to work

Time:10-30

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

int main()
{
    srand(time(NULL)); // initiates random number generation
    int CpuGuess;
    int IsCorrect;
    int HigherLower;
    int lower,higher;


    printf("Think of a number from 1-9, keep it in mind.\n");
   
    CpuGuess = rand() % 10; //cpu guesses number between 1-9

    printf("Is your number %d? Yes = 1, No = 2, Enter here: ", CpuGuess);
    scanf("%d",&IsCorrect);  // asks if its 1 or 2 depending if correct or false

    while(IsCorrect == 2)
    {
        
        printf("Is your number higher or lower?, lower = 1, higher = 2");
        scanf("%d",&HigherLower);


        if(HigherLower==1)
        {
            lower == 0;
            higher = CpuGuess;
            CpuGuess = (rand() % (higher - lower 1))   lower;
            printf("Is your number %d?", CpuGuess);
        }
        else if(HigherLower==2)
        {



        }

    }

    if(IsCorrect == 1)
    {

        printf("I have guessed your number!");

    }

}

Cant get the guess to be between the higher bound and lower bound its guessing ridiculous number s like 460 and stuff like that and the more i say lower it goes down but only to a certain point and its different each time(still 400 )

CodePudding user response:

so as I have already commented, the problem seems to be with lower == 0. This is a comparison, not an assignment, so at this point, the lower variable is never initialized, and thus if you execute CpuGuess = (rand() % (higher - lower 1)) lower; the lower variable creates undefined behaviour as we have no idea, what value that variable actually has.

Simple fix is to change lower == 0; to lower = 0; and it should work fine.

  •  Tags:  
  • c
  • Related