所以我正在创建一个随机数生成器,但我不断遇到问题。在我的程序中,我将代码打印到“int main()”函数中。问题是它之后打印了 0。它还说我必须使用 return,但我不想这样做。我想将随机数生成器保留在另一个函数中,因为我将来会添加更多。
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int randRoll();
//Calls the other function
int main()
{
cout << randRoll() << endl;
system("Pause");
}
//Gets the random number
int randRoll()
{
srand(time(0));
for (int x = 1; x <= 1; x ++)
{
cout <<"Your random number is " << 1 +(rand()%4) << endl;
}
return 0;
}
最佳答案
试试这个:
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int randRoll();
// entry point
int main()
{
srand(time(0)); // initialize randomizer
cout << randRoll() << endl;
system("Pause");
return 0;
}
//Gets the random number
int randRoll()
{
auto x = 1 +(rand()%4);
// do something with x here (but don't call cout!)
return static_cast<int>(x);
}
您遇到的问题是您没有返回随机生成的值(我在代码中将其称为x
)。另外,您尝试两次打印随机生成的值(但错误)。
关于c++ - 返回值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20441088/