Make this run till it reaches max

This will run once with no problems. But if I switch the while condition then it goes to infinite loop. This is what I am trying to do:
How would I make it run so current_total would add until it reached total and stopped. Also print how many tries it took to do so. Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
# include <time.h>
using namespace std;




int main()
{

int maximum;
int minimum;
int random_number;
int req_subtraction;
int current_total;
int total;


cout << "Total Limit?" << endl;   //can't go over this
cin >> total;

cout << "Max you can add?" << endl;
cin >> maximum;

cout << "Minimum you can add?" << endl;
cin >> minimum; 

cout << "Required Subtraction?" << endl;
cin >> req_subtraction; 

srand(time(0));  //seed the random number
	
int high=maximum;
int low=minimum;


do
{
random_number = rand () % (high - low + 1) + low;//random number between max and min


cout << "Random Number is " << random_number << endl;

current_total = random_number - req_subtraction;

	if(current_total < 0)   //make so negatives equal out to zero
	{
    current_total = 0;
	} while(current_total < 0);
 


cout << "The current total is " << current_total << endl;

if (current_total >= total) //if current total goes over the max then set to max
{
	current_total = total;
}

}
while (current_total > total); //if I set the > to < it goes to infinite loop

system("pause");
return 0;
}
I'm not quite sure what you are trying to do, but an endless loop occurs due to the way you wrote your code. Your current_total is always going to be less than or equal to total. Notice that your last if statement will never let current_total be greater than total. I'm not sure what your trying to do with line 49 either. Your syntax is incorrect.
Last edited on
why do you have two while statements?

also, try current_total += random_number - req_subtraction;

I think the idea here is that you keep looping until the current_total arrives at either the total, or some value that is over the total so that we can set current_total to the max value.

when you do this:

current_total = random_number - req_subtraction;

current_total never accumulates, it just keeps getting reassigned.
this is why it always helps to have multiple eyes. thanks a ton. I'll rework the code and get back if I have any more ?'s
Topic archived. No new replies allowed.