0
#include<iostream>
using namespace std;
int main()
{


    int rnd = 1 + (rand() % 99999);
    char comp;
    cout << "Introduzca el valor a comparar" << endl;

    cin >> comp;

    if (comp > rnd)
    {
        cout << ">";
    }
    else if (comp < rnd)
    {
        cout << "<";
    }
    else if (comp = rnd)
    {
        cout << "=";
    }
}

So, in this C++ program I'm trying to get the user to guess a number, but I want them to have a limited number of tries at guessing (20). I have basically zero experience in C++ and I don't know how to implement this system.

  • 2
    Have you considered using a [`for`](https://en.cppreference.com/w/cpp/language/for) loop? – Captain Obvlious Dec 29 '22 at 22:40
  • 1
    Think of how you would do this without a computer. You'd keep a count of the number of tries and kick the player ut when they've run out of tries. And while you at it, `else if (comp = rnd)` is an accidental assignment. You want `==`. – user4581301 Dec 29 '22 at 22:41
  • `int rnd = 1 + (rand() % 99999);` - 1) using a C generator with really poor properties. 2) using modulo in a way that biases the random numbers. – Jesper Juhl Dec 29 '22 at 22:45
  • And using a modulo that [may exceed `RAND_MAX`](https://en.cppreference.com/w/cpp/numeric/random/RAND_MAX) – user4581301 Dec 29 '22 at 22:50
  • 1
    PSA: `=` and `==` are **vastly different**. When learning you must learn to spot mistakes like this. I immediately noticed it, but it's only because I look specifically for things like this. – tadman Dec 29 '22 at 23:00
  • Tip: If you've excluded all other possibilities, use a default `else` at the end. This avoids mistakes. Your code only "works" by sheer chance. If you reorder the `if` statements it breaks. – tadman Dec 29 '22 at 23:01
  • Hint: `while (guesses < max_guesses)` – tadman Dec 29 '22 at 23:02
  • Sorry for all of the beginner mistakes, kinda threw myself at the problem without checking tutorials. – communistfunnyman Dec 29 '22 at 23:20
  • Not only is `comp = rnd` an accidental assignment, it's wholly unnecessary. You've already eliminated the possibilities `comp > rnd` and `comp < rnd`. What other state could exist aside from `comp == rnd`? – Chris Dec 30 '22 at 00:01
  • And no one's mentioned yet that you won't get a different random number when you re-run the program. Your sequence is deterministic. – sweenish Dec 30 '22 at 02:52
  • Be cautious with tutorials. Until you have enough familiarity with the language to detect frauds and madmen, you have to do extra research to establish the credibility of the tutorial's writer. Sucks to invest a bunch of time into writing code based on the rantings of a lunatic or some overconfident know-nothing trying to generate ad revenue. The best way to gain familiarity is through a well-curated resource like a [good book](https://stackoverflow.com/q/388242/4581301). – user4581301 Dec 30 '22 at 06:32

0 Answers0