我有这个代码。我正在生成2个具有随机数的数组,然后使用arrayToString函数从这些数组中创建2个字符串,但是我的输出很奇怪。

class job1Instance : public pp::Instance {
public:
        explicit job1Instance(PP_Instance instance): pp::Instance(instance) {}
        virtual ~job1Instance() {}

    virtual void HandleMessage(const pp::Var& message) {
        // declare all the zises
        int32_t minNum = 1;
        int32_t maxNum = 100;
        int32_t arrayElements = maxNum;

        // the arrays
        int32_t unsorted1[arrayElements/2];
        int32_t unsorted2[arrayElements/2];

        // fill the arrays with random numbers
        unsortedArrays(unsorted1, unsorted2, arrayElements, minNum, maxNum);
        std::string outRes1, outRes2, jsonStr;
        arrayToString(unsorted1, arrayElements/2, outRes1);
        arrayToString(unsorted2, arrayElements/2, outRes2);
        PostMessage(pp::Var(outRes2));
    }



private:
    // function to create a random number between min and max
    int32_t rangeRandomAlg (int32_t min, int32_t max) {
        int32_t num = max - min + 1;
        int32_t remainder = RAND_MAX % num;
        int32_t x;
        do {
            x = rand();
        } while (x >= RAND_MAX - remainder);
        return min + x % num;
    }

    // function to create arrays with random numbers
    void unsortedArrays (int32_t unsorted1[], int32_t unsorted2[], int32_t arrayElements, int32_t &minNum, int32_t &maxNum) {
        for(int32_t i = 0; i < arrayElements; i++) {
            if (i < arrayElements/2) {
                //unsorted1[i] = rangeRandomAlg(minNum, maxNum);
                unsorted1[i] = rand() % maxNum + minNum;
            } else {
                //unsorted2[i] = rangeRandomAlg(minNum, maxNum);
                unsorted2[i] = rand() % maxNum + minNum;
            }
        }
    }


    // convert the arrays to string
    void arrayToString (int32_t array[], int32_t arraySize, std::string& arrayString) {
        for (int i = 0; i <= arraySize; ++i){
            arrayString+= std::to_string(array[i]);
            if (i != arraySize) {
                arrayString+= ',';
            }
        }
    }

有人可以告诉我为什么我的outRes2输出包含这些数字吗?



根据我的minNummaxNum的定义,它们显然不在1到100之间,我找不到问题。

最佳答案

您声明了两个数组,每个数组的大小为arrayElements/2:

    int32_t unsorted1[arrayElements/2];
    int32_t unsorted2[arrayElements/2];

您的循环将它们初始化如下:
        if (i < arrayElements/2) {
            //unsorted1[i] = rangeRandomAlg(minNum, maxNum);
            unsorted1[i] = rand() % maxNum + minNum;
        } else {
            //unsorted2[i] = rangeRandomAlg(minNum, maxNum);
            unsorted2[i] = rand() % maxNum + minNum;
        }

因此,例如,当i的值达到arrayElements/2时,else语句的if部分将执行:
            unsorted2[arrayElements/2] = rand() % maxNum + minNum;

由于unsorted2的大小为arrayElements/2,因此此数组仅包含unsorted2[0]unsorted2[arrayElements/2-1]值,并且此赋值从数组末尾开始,从而导致未定义的行为。

关于c++ - 生成随机数出错,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39320093/

10-13 08:47