随机数(rand)不能输出未知字符

Random Number (rand) does not work outputting an unknown character

本文关键字:输出 未知 字符 不能 rand 随机数      更新时间:2023-10-16

我正在尝试创建一个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 . . .

所以随机数生成器不能正常工作,但我不知道为什么会发生。有人能帮我解决这个问题或建议一个更好的方法来生成随机数吗?

问题不在于rand()。问题是您将pile1声明为std::string,因此试图将rand()的返回值分配给pile1,这将不起作用,因为rand()返回int

pile1更改为int,或将整数返回值转换为字符串:

int pile1;
//...
pile1 = rand%40 + 1;

实例1

std::string pile1;
//...
pile1 = std::to_string(rand() % 40 + 1);

实例二


同样,std::string的正确#include

#include <string>

而非

#include <string.h>

如果你将代码更改为以下代码可能会得到最好的结果:

#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;
}