c++ - C++ 随机 ID 和随机答案
问题描述
我正在制作一个输出 ID 和随机猜测答案的程序。你可以猜出 A、B、C、D,ID 的前 2 个字母是随机字符,后 3 个是数字。
错误是程序给了我这样的 ID:YN420BBBBCBACDBBCDB
您可以清楚地看到其中的ID。但是,它把随机答案和它放在一个变量中。这是我的代码:
#include <iostream>
#include <stdio.h>
#include <ctime>
#include <cstdlib>
#include <string>
#include <fstream>
using namespace std;
char id[6];
char answers[16];
int main()
{
srand(time(NULL));
int random =rand() % 500+1;
const char* const a_to_d = "ABCD" ;
const char* const a_to_z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
const char* const zero_to_seven = "01234567";
for (int i = 0; i < random; ++i){
int ri = rand() % 26;
id[0] = a_to_z[ri];
int ri1 = rand() % 26;
id[1] = a_to_z[ri1];
int ri2 = rand() % 7;
id[2] = zero_to_seven[ri2];
int ri3 = rand() % 7;
id[3] = zero_to_seven[ri3];
int ri4 = rand() % 7;
id[4] = zero_to_seven[ri4];
id[6] = 0;
cout<<id<<" "<<answers<<endl<<endl;
int fi = rand() % 4;
answers[0] = a_to_d[fi];
int fi1 = rand() % 4;
answers[1] = a_to_d[fi1];
int fi2 = rand() % 4;
answers[2] = a_to_d[fi2];
int fi3 = rand() % 4;
answers[3] = a_to_d[fi3];
int fi4 = rand() % 4;
answers[4] = a_to_d[fi4];
int fi5 = rand() % 4;
answers[5] = a_to_d[fi5];
int fi6 = rand() % 4;
answers[6] = a_to_d[fi6];
int fi7 = rand() % 4;
answers[7] = a_to_d[fi7];
int fi8 = rand() % 4;
answers[8] = a_to_d[fi8];
int fi9 = rand() % 4;
answers[9] = a_to_d[fi9];
int fi10 = rand() % 4;
answers[10] = a_to_d[fi10];
int fi11 = rand() % 4;
answers[11] = a_to_d[fi11];
int fi12 = rand() % 4;
answers[12] = a_to_d[fi12];
int fi13 = rand() % 4;
answers[13] = a_to_d[fi13];
int fi14 = rand() % 4;
answers[14] = a_to_d[fi14];
answers[16] = 0;
}
return 0;
}
解决方案
您的 char 数组需要以空值结尾。由于不是,cout 继续进入下一个数组,直到最终找到一个空终止符。要解决此问题,只需将长度增加一char id[5]
并将最后一个值设置为 0id[4] = 0
此外,您的模数运算符永远不会覆盖 ri 和 ri2 的最后一个值。rand() % 25
你能得到的最大值是 24。你实际上想要rand() % 26
.
推荐阅读
- powershell - Windows 事件查看器 xPath 查询不适用于某些字符串。转义字符?
- macos - 在 Mac 上的终端输出上搜索文本(不使用终结器)
- javascript - 无法设置未定义的已选中(保存带有 localStorage 的复选框)
- mysql - postgres:在用户首次登录时强制更改密码
- typescript - 如何将 NestJS 配置注入 TypeORM 实体?
- html - 改变相同属性的多个 CSS 类
- java - Java OffsetDateTime 显示奇怪的年份值
- asp.net-web-api2 - .NetCore 3.1 API 在将 Asp.NetCore.Odata 用于 REST API 时出现问题
- python - 重命名数据框中具有相似名称的行值
- delayed-job - 如何与不同的工作人员正确运行监控