首页 > 解决方案 > 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;
        }

标签: c++char

解决方案


您的 char 数组需要以空值结尾。由于不是,cout 继续进入下一个数组,直到最终找到一个空终止符。要解决此问题,只需将长度增加一char id[5]并将最后一个值设置为 0id[4] = 0

此外,您的模数运算符永远不会覆盖 ri 和 ri2 的最后一个值。rand() % 25你能得到的最大值是 24。你实际上想要rand() % 26.


推荐阅读