The goal of this program is to have a random number generator that I can use in the main through a function. Then the values from the random number generator will trigger an action. This has if statements checking the values from the generator. The problem I am having is both strings, "Numbers 1 - 5" and "Numbers 6 - 10" appear instead of the if statements triggering only what is expected from them which would make only one of the strings appear.
#include <iostream>
#include <string>
#include <chrono>
void main()
{
void RanNum1to10();
int RanNum;
int x;
std::cin >> x;
if (x == 2)
{
std::cout << "X = 2" << std::endl << std::endl;
RanNum1to10();
if (RanNum = 1||2||3||4||5)
{
std::cout << "Number 1 - 5" << std::endl;
}
if (RanNum = 6||7||8||9||10)
{
std::cout << "Number 6 - 10" << std::endl;
}
}
system("pause");
}
void RanNum1to10()
{
(time(0));
int RanNum;
int x = 1+(rand() % 9 + 1);
switch(x)
{
case 1:
RanNum = 1;
case 2:
RanNum = 2;
case 3:
RanNum = 3;
case 4:
RanNum = 4;
case 5:
RanNum = 5;
case 6:
RanNum = 6;
case 7:
RanNum = 7;
case 8:
RanNum = 8;
case 9:
RanNum = 9;
default:
RanNum = 10;
}
}
Thank you.
You need to use
instead of
Similarly for the other
if
statement.That's one problem.
The other problem is that you have the line:
in
main
but you have not assigned any value to it.You have assigned values to a local variable of the same name in
RanNum1to10
but that won't change the value ofRanNum
inmain
.You can address that problem by changing the return vaule of
RanNum1to10
toint
, and returning the random number from it, and assigning the return value ofRanNum1to10
toRanNum
.Change the line
to
Change the line
to
Change the implementation of
RanNum1to10
to:Update, in response to comment by OP
Due to operator precedence, the expression
if (x = 2||3||4)
is equivalent toif ( x = (2 || 3 || 4) )
, which is equivalent tox = 1; if ( x )
. As you can see, the conditional of such anif
statement always evaluates to true.First problem:
if (x = 2)
should beif (x == 2)
. Otherwise you're just testing the result of an assignment, which is equal to the number being assigned. The compiler should have generated a warning for this.Second problem: to test against multiple values, you can't just
or
the values together with||
. The result of such an expression will be true or false, equating to 1 or 0. You need to expand out each comparison:Of course in this particular case you can simplify the condition: