In this loop, x is incremented one too many times.
int x = 0;
while (x < 10)
{
x = x + 3;
}
cout << x;
The output for this is 12, when i want it to be 9. Generally speaking, how would I find the last value of a sequence (in this case 9) given a restraint ( in this case 10).
For example:
int last = 0;
for (int x = 0; x < 10; x+=3)
{
last = x;
}
cout << last;
or:
int x = 0;
while (x < 10)
{
x = x + 3;
}
cout << x - 3;
or:
int x = 0;
int last = 0;
while (x < 10)
{
last = x;
x = x + 3;
}
cout << last;
or:
int x = 0;
while (x + 3 < 10)
{
x = x + 3;
}
cout << x;
Using your code you can try:
int x = 0;
while (x+3 < 10)
{
x = x + 3;
}
cout << x;
If you want to see the last value, it is better to decrease it by the same amount you are incrementing it.
int x = 0;
while (x + 3 < 10)
{
x = x + 3;
}
x = x -3;
Another way to do this is to use a break statement inside the loop with a suitable condition with which you want to leave it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.