随机数(rand)不能输出未知字符
Random Number (rand) does not work outputting an unknown character
我正在尝试创建一个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;
}
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 请解释"函数1(p1,p2,p3);"的输出
- C++:将控制台输出存储在宏中更好吗
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 继承期间显示未知行为的子类
- 如何在OMNET++中指定与命令行参数组合的输出文件名
- 为什么我的代码在输出中增加了93天
- 如何从void函数输出字符串
- C++ 读取未知数量的整数到 cin 并输出总和
- 二次方程求解器输出以未知格式输出
- 使用数组和布尔值在输出未知时从输出中删除逗号
- 使用数组查找HCF,获取未知输出(C )
- C++ 继承和多态性未知输出
- 未知(内存损坏)错误.sprintf_s输出
- 如何将未知数量的元素输出到标准容器
- Codeforces 268B -未知值作为这个小c++程序的输出
- 如何在c++中写入/读取未知的输入/输出流
- 随机数(rand)不能输出未知字符
- C++中的未知输出