随机数生成函数 [英] Random Number Gen as function
问题描述
该程序的目标是要有一个随机数生成器,我可以通过一个函数在主机上使用它.然后,来自随机数生成器的值将触发一个操作.它具有if语句,用于检查生成器中的值.我遇到的问题是两个字符串,都出现数字1-5"和数字6-10",而不是if语句仅触发期望的内容,从而只会出现其中一个字符串.
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;
}
}
谢谢.
推荐答案
您需要使用
if ( (RanNum == 1) ||
(RanNum == 2) ||
(RanNum == 3) ||
(RanNum == 4) ||
(RanNum == 5) )
代替
if (RanNum = 1||2||3||4||5)
与其他 if
语句类似.
那是一个问题.
另一个问题是您所在的行:
The other problem is that you have the line:
int RanNum;
在 main
中,但是您尚未为其分配任何值.
in main
but you have not assigned any value to it.
您已在 RanNum1to10
中为同名的局部变量分配了值,但不会更改 main
中的 RanNum
的值
You have assigned values to a local variable of the same name in RanNum1to10
but that won't change the value of RanNum
in main
.
您可以通过将 RanNum1to10
的返回值更改为 int
并从中返回随机数,并分配 RanNum1to10的返回值来解决该问题.
到 RanNum
.
You can address that problem by changing the return vaule of RanNum1to10
to int
, and returning the random number from it, and assigning the return value of RanNum1to10
to RanNum
.
更改行
void RanNum1to10();
到
int RanNum1to10();
更改行
RanNum1to10();
到
RanNum = RanNum1to10();
将 RanNum1to10
的实现更改为:
int RanNum1to10()
{
return (rand() % 10 + 1);
}
更新,以回应OP的评论
由于运算符优先级,表达式 if(x = 2 || 3 || 4)
等效于 if(x =(2 || 3 || 4))
,等效于 x = 1;如果是(x)
.如您所见,这样的 if
语句的条件始终为true.
Due to operator precedence, the expression if (x = 2||3||4)
is equivalent to if ( x = (2 || 3 || 4) )
, which is equivalent to x = 1; if ( x )
. As you can see, the conditional of such an if
statement always evaluates to true.
这篇关于随机数生成函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!