=0;i--){ srand(时间(空)); int j=rand(); cout,c++,C++" /> =0;i--){ srand(时间(空)); int j=rand(); cout,c++,C++" />

在c+中向rand()添加模数+;影响for循环外的执行,为什么以及如何补救? 我是C++初学者,我希望你能帮我一些有趣的东西,你们都知道我的意思。 这是一个C++代码的片段,我将简要地解释一下我的问题: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { // this first for loop doesn't affect the execution of the first cout statement. for (int i = 51; i >= 0; i--) { srand(time(NULL)); int j = rand(); cout << j << endl; }; cout << "first cout outside the first for loop" << endl; // executes fine // this second for loop affects the execution of the following cout statement. for (int i = 51; i >= 0; i--) { srand(time(NULL)); int j = rand() % i; //by just adding % i, the next cout statement doesn't execute! cout << j << endl; }; cout << "second cout outside the second for loop" << endl; // doesn't execute } #包括 #包括 #包括 使用名称空间std; int main(){ //这个first for循环不会影响第一个cout语句的执行。 对于(int i=51;i>=0;i--){ srand(时间(空)); int j=rand(); cout

在c+中向rand()添加模数+;影响for循环外的执行,为什么以及如何补救? 我是C++初学者,我希望你能帮我一些有趣的东西,你们都知道我的意思。 这是一个C++代码的片段,我将简要地解释一下我的问题: #include <iostream> #include <ctime> #include <cstdlib> using namespace std; int main() { // this first for loop doesn't affect the execution of the first cout statement. for (int i = 51; i >= 0; i--) { srand(time(NULL)); int j = rand(); cout << j << endl; }; cout << "first cout outside the first for loop" << endl; // executes fine // this second for loop affects the execution of the following cout statement. for (int i = 51; i >= 0; i--) { srand(time(NULL)); int j = rand() % i; //by just adding % i, the next cout statement doesn't execute! cout << j << endl; }; cout << "second cout outside the second for loop" << endl; // doesn't execute } #包括 #包括 #包括 使用名称空间std; int main(){ //这个first for循环不会影响第一个cout语句的执行。 对于(int i=51;i>=0;i--){ srand(时间(空)); int j=rand(); cout,c++,C++,执行未定义行为的程序可以有任何明显的行为,包括“过去”不执行的代码 在循环结束时,您可以执行代码> %0,/COD>。这使得早期的打印语句不输出。这是C++所能接受的行为。 不要做未定义的行为。在程序开始时调用srand一次。rand()%0是UB。感谢Neil,这是一个很好的建议,但是,第二个cout语句未执行的问题仍然存在!endl应该刷新,但可能会备份您的cout语句,并在程序因上述rand()而崩溃时等待打印%0;使用开发环境随附的调试器逐步完成程序,看看会发生什么。我现在明白了,问题是

执行未定义行为的程序可以有任何明显的行为,包括“过去”不执行的代码

在循环结束时,您可以执行代码> %0,/COD>。这使得早期的打印语句不输出。这是C++所能接受的行为。


不要做未定义的行为。

在程序开始时调用srand一次。
rand()%0
是UB。感谢Neil,这是一个很好的建议,但是,第二个cout语句未执行的问题仍然存在!
endl
应该刷新,但可能会备份您的
cout
语句,并在程序因上述
rand()而崩溃时等待打印%0;
使用开发环境随附的调试器逐步完成程序,看看会发生什么。我现在明白了,问题是取模超过零,我的错。谢谢各位。我现在明白了,问题是取模超过零,我的错。谢谢亚克。