- #1
fluidistic
Gold Member
- 3,949
- 264
I don't understand why I enter in an infinite loop with the following code:
The idea is to generate a random number between 1 and 3, write it into a file. Repeat until the new random number differs by either +1 or -1 from the previous random number. With the current code, the loop never ends and in a matter of a few seconds my file.txt is filled by 1's, 2's and 3's up to several Mb's.
As I understand it, my do {...} wile(x-xold!=1 && x-xold!=-1) should continue when x-xold is not equal to 1 and when x-xold is not equal to -1. So if I get xold=0 and x=1, then x-xold=1 and the loop should stop because the first condition is not satisfied... but it doesn't stop at all.
I guess my logic is flawed but I'm blind and don't see it. Any help will be appreciated.
P.S.:I started c++ 5 days ago for fun.
Code:
#include <iostream> //for cout
#include <cstdlib> //for rand()
#include <ctime> // for time()
#include <fstream> //to write into a text file
using namespace std;
static const int M = 3;
ofstream myfile;
int main()
{
srand(time(0)); // set initial seed value to system clock
myfile.open("data.txt", ios::app);
int x=0;
int xold=0;
int i;
do
{
int xold=x;
int x = rand() % M+1;
myfile << x << endl;
i++;
}
while(x-xold!=1 && x-xold!=-1);
cout << "It took" << i << "iterations" << endl;
return 0;
myfile.close();
}
The idea is to generate a random number between 1 and 3, write it into a file. Repeat until the new random number differs by either +1 or -1 from the previous random number. With the current code, the loop never ends and in a matter of a few seconds my file.txt is filled by 1's, 2's and 3's up to several Mb's.
As I understand it, my do {...} wile(x-xold!=1 && x-xold!=-1) should continue when x-xold is not equal to 1 and when x-xold is not equal to -1. So if I get xold=0 and x=1, then x-xold=1 and the loop should stop because the first condition is not satisfied... but it doesn't stop at all.
I guess my logic is flawed but I'm blind and don't see it. Any help will be appreciated.
P.S.:I started c++ 5 days ago for fun.