I'm learning C ++.
In that case, allow me to welcome you \ñ_ñ/
and give you some tips:
- Headers
<stdlib.h>
and <time.h>
are from c not from c ++ . These headers have a version adapted to C ++ that has the prefix c
and has no extension. If you really need to use the C headers (which will never be the case) you should use the C ++ equivalents <cstdlib>
and <ctime>
. Read this thread to find out why.
- There is no obligation to use the
using namespace std;
clause since it is only an aid to the writing of code; If you decide to use this clause do not do it in the global scope, use it in the smallest possible scope. Read this thread to find out why.
- The
rand()
and srand()
functions belong to the C libraries, it is discouraged to use those C ++ utilities because they may not be portable and may offer questionable results and performance, therefore is being studied deprecarlo . From the C ++ 11 standard there is a complete library of generation of pseudo-random numbers that you should use instead. Read this thread to find out why.
The idea is that when the variable vida
or evida
reach 0
stop the while
, but instead wait for the 2 variables are less than or equal to 0
.
That is the expected behavior; in a condition joined by an or ( ||
) the expression will be true as long as any of the expressions is true and consequently it will be false when both expressions are true:
| tabla de la verdad OR |
+-------------+-------------+----+-----------+
| expresión 1 | expresión 2 | || | resultado |
+-------------+-------------+----+-----------+
| falso | falso | || | falso |
| falso | verdadero | || | verdadero |
| verdadero | falso | || | verdadero |
| verdadero | verdadero | || | verdadero |
You want a condition and ( &&
), which will be true when all the expressions are true and therefore will be false in the other cases:
| tabla de la verdad AND |
+-------------+-------------+----+-----------+
| expresión 1 | expresión 2 | && | resultado |
+-------------+-------------+----+-----------+
| falso | falso | && | falso |
| falso | verdadero | && | falso |
| verdadero | falso | && | falso |
| verdadero | verdadero | && | verdadero |
Therefore your while
, with and ( &&
):
while(vida >= 0 && evida >= 0)
It could be read as " As long as vida
is greater than or equal to 0
and evida
is greater than or equal to 0
".