gpt4 book ai didi

c++ - 随机数 (rand) 无法输出未知字符

转载 作者:行者123 更新时间:2023-11-27 22:49:13 25 4
gpt4 key购买 nike

我正在尝试创建一个 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() returns an int 起将不起作用.

要么改pile1int , 或将整数返回值转换为字符串:

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

Live Example 1

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

Live Example 2


此外,适当的 #include对于 std::string

#include <string>

而不是

#include <string.h> .

关于c++ - 随机数 (rand) 无法输出未知字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39303067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com