mercredi 18 janvier 2023

How do I choose a random number from a list?

I am creating a number-guessing game where the player has to guess a randomly generated number but I don't know how to choose a random number.

I have a variable called truenumber which is equal to a list of numbers, what I want to do is make it randomly choose from the list and compare it to the user's input.

    int truenumber; 
    truenumber = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;

So how do I make it pick a random number from the list each time?

#include <iostream>
using namespace std;

int main() {
    
    string message = "Hello";
    cout << message << endl;
    cout << "Lets play a game" << endl;
    cout << "Try to guess the number!" << endl;
 
    int truenumber; 
    truenumber = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
    int number;
    cin >> number;

    if (number = truenumber) {   
        cout << "You got it right!" << endl;
    }
    else if (number > truenumber) {
        cout  << "Too high" << endl;
        cin >> number;
    }
    else (number < truenumber) {
        cout << "Too low" << endl;
        cin >> number;
    }
    
} 

I wasn't expecting this to work since truenumber doesn't have an actual value and I was trying to find a solution online but only found really complex solutions that didn't match my ideas.




Aucun commentaire:

Enregistrer un commentaire