我正在尝试创建一个nim游戏,我正在尝试生成游戏中使用的随机数,但它不起作用。这是我的代码:
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
string player1name,player2name,player1status,player2status,pile1,pile2,pile3;
int main(){
cout<<"What is player 1's name?"<<endl;
getline(cin, player1name);
cout<<"What is player 2's name?"<<endl;
getline(cin, player2name);
pile1 = rand() % 40 + 1;
cout<<pile1;
return 0;
}
它成功编译,但其输出如下:
What is player 1's name?
Ttyeuo yuwew
What is player 2's name?
Yiefwh HYoaw
?
--------------------------------
Process exited after 15.84 seconds with return value 0
Press any key to continue . . .
因此随机数生成器无法正常运行,但我无法弄清楚它为什么会发生。有人可以帮我解决这个问题或建议一个更好的方法来生成随机数吗?
答案 0 :(得分:3)
问题不在于rand()
。问题是您将pile1
声明为std::string
,因此尝试将rand()
的返回值分配给pile1
,这将自rand() returns an int
起无效
将pile1
更改为int
,或将整数返回值转换为字符串:
int pile1;
//...
pile1 = rand%40 + 1;
或
std::string pile1;
//...
pile1 = std::to_string(rand() % 40 + 1);
此外,#include
的正确std::string
是
#include <string>
而不是
#include <string.h>
。
答案 1 :(得分:1)
如果您将代码更改为此代码,则可能获得最佳结果:
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
int main(){
cout<<"What is player 1's name?"<<endl;
string player1name,player2name,player1status,player2status,pile1,pile2,pile3;
cin >> player1name;
cout<<"What is player 2's name?"<<endl;
cin >> player2name;
pile1 = rand() % 40 + 1;
cout << pile1;
return 0;
}