首页 > 解决方案 > 当我使用该变量时,为什么我的 c++ 程序会错误地工作?

问题描述

我有一个功能:

#include "motHasard.h"

    std::string motHasard(std::string mot)
    {
        srand(time(0));
        std::string motnew("");
        int position;
        while(mot.size()!=0)
        {
    
            position = rand() % mot.size();
    
            motnew+=mot[position];
            mot.erase(position,1);
        }
        return motnew;
    }

如果我使用变量而不是mot.size()(在while, 或 for 中position)并运行程序,它会在 main() 调用函数时停止并出错motHasard。但就像那样,它完美地工作。

为什么我不能将变量放入.size()变量中并使用它?

像那样 :

#include "motHasard.h"

    std::string motHasard(std::string mot)
    {
        srand(time(0));
        std::string motnew("");
        int taille=mot.size();
        int position;
        while(taille!=0)
        {
    
            position = rand() % taille;
    
            motnew+=mot[position];
            mot.erase(position,1);
        }
        return motnew;
    }

这个不行

标签: c++variables

解决方案


您忘记了需要重新计算变量的值,这是您的代码:

        int taille=mot.size();
        int position;
        while(taille!=0)
        {
    
            position = rand() % taille;
    
            motnew+=mot[position];
            mot.erase(position,1);
        }

因此,您从tailleCURRENT 大小开始mot(想象它是 12)。
只要不重新计算,即使发生mot变化,该值也将保持为 12,因此需要进行以下更正:

        int taille=mot.size();
        int position;
        while(taille!=0)
        {
    
            position = rand() % taille;
    
            motnew+=mot[position];
            mot.erase(position,1);
            taille=mot.size();           // <--- never forget to re-calculate the while-variable
        }

推荐阅读