Ho un programma C di base che produce un numero e l'utente deve indovinarlo (sì, lo hai già chiamato: compiti a casa). Sono in grado di ottenere più o meno tutto, quindi sono un po 'orgoglioso, ma apro gli errori che ho fatto, ovviamente sto ancora imparando. Le mie due domande principali sonoCome terminare un ciclo all'inizio di C?
- Come posso terminare questo programma in anticipo quando l'utente ha selezionato il numero corretto, prima che abbia raggiunto il numero 10 di tentativi? E
- Eventuali errori evidenti a un guru possono vedere che io non sono con il mio codice?
che sto cercando di programmare come meglio posso :)
int main(void)
{
int x = 10;
int i = 0;
int target, guess;
int numGuess = 0;
/*create a random number*/
//create random function
srand(time(NULL));//this creates new number based on time which changes every second :)
target = rand() % 99; //create a random number using the rand() function, from 0 -99
do{
//increase the loop until it meets the x variable
i++;
numGuess++;
//allow user to input a number for guess
scanf("%d", &guess);
if (guess == target)
{
printf("You win! \n\n");
}
else if (guess > target)
{
printf("You are too high. Guess a number:\n\n");
}
else if (guess < target)
{
printf("You are too low. Guess a number:\n\n");
}
}while(i < x);
printf("You lose, the number was %d. \n", target);
printf("Number of tries %d\n", numGuess);
printf("Enter any key to exit...");
getchar();
getchar();
return 0;
}
Ti è stata insegnata la struttura del programma di base, cicli do/while, IO, sscanf, rand, seeding del rng, ma non 'break'? – Jason
È bello vedere che hai commentato il tuo codice - ben fatto: D –
Perché hai due chiamate getchar() alla fine, quando dici che vuoi solo 1 tasto per terminare il programma? –