Reputation: 97
I have a code that is supposed to reduce a variable, by one in each iteration, in a loop. The problem is that it does not, it remains the same. Here is the code I have:
bool IsRed(int speed, int distance, int time)
{
if ((18 * distance) % (10 * speed * time) >= (5 * distance * time)) {return true;}
return false;
}
std::vector<std::pair<int, int> > DistanceTime = {{ 300,10 }, { 1500,10 }, { 3000,10 }};
int maxSpeed = 90 * 0.277778;
int traficLights = 3;
for (int i = 0; i < traficLights; i++)
{
for (auto j = DistanceTime.begin(); j != DistanceTime.end(); ++j)
{
int distance = j->first;
int time = j->second;
if (IsRed(maxSpeed, distance, time) == true)
{
maxSpeed--; //should get reduced
i = 0;
j = DistanceTime.begin();
}
//debug line
std::cout << maxSpeed * 3.6 << std::endl; //didn't change
}
}
The variable maxSpeed should get reduced every time the IsRed() function returns "true". Then the first and second for loop should re-initialize and test the new reduced speed again. At the end, the maxSpeed that returns "false", for all the pairs of the vector, in the IsRed() function, should be printed (did not do it in the code above).
Have I messed up the for loops? Any help would be very welcome!
Upvotes: 0
Views: 104
Reputation: 502
In order for any code within:
if (IsRed(maxSpeed, distance, time) == true)
{
//stuff
}
to be executed, your function IsRed(...) needs to return true, and with the inputs you provided it doesn't.
you also don't need to specify == true
in your if statement you can simply write:
if (IsRed(maxSpeed, distance, time))
{
//stuff
}
because of the return type of the function IsRed.
Upvotes: 2