c++ - 当我使用该变量时,为什么我的 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;
}
这个不行
解决方案
您忘记了需要重新计算变量的值,这是您的代码:
int taille=mot.size();
int position;
while(taille!=0)
{
position = rand() % taille;
motnew+=mot[position];
mot.erase(position,1);
}
因此,您从taille
CURRENT 大小开始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
}
推荐阅读
- c# - 如何提取列表对象的属性并传递到存储过程
- crystal-reports - Crystal Report - 仅在存在某些代码时显示行
- excel - Excel 宏 vlookup R1C1 性能问题
- excel - 通过 VBA 选择的单元格范围不起作用
- java - JAVA运行多个链接类
- powershell - 如何使用 POST 命令将客户端添加到 Clockify 工作区?
- python - 升级 Pandas/Numpy 后 for-loop 不起作用
- cmake - 使用 cmake 在构建期间生成脚本
- flutter - 在 Mobx Flutter 中扩展 store 类
- python - cent OS ImportError: libedgetpu.so.1: 无法打开共享对象文件