For loop only works half of times specified

I"m trying to count the # of successful outcomes of running a certain test (code is not given below).
I need a loop that runs the test for 20 times and prints out the rate of success out of 20 times.
I don't know why but my loop only prints an output only 10 times! This always is the case even when I change the ending condition to any number other than 20.

Attached is only the relevant pieces of the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
double successRate = 0; //initialize variable recording total times of successes of test
  for (int count = 1; count <= 20; count++)
    {
        string result = sf(fliptest()); //result of running the test the first time, only gives 
//one of two strings: "success" or "failure"
        if (result =="success")
        {
            successRate++;
            cout << result << endl;
            count++;
        }
        else
        {
            cout << result << endl;
            count++;
        }
    }
 cout << "The % of success is" << (successRate/20)*100 << " %" << endl;


Thanks!
Last edited on
Remove
 
count++


from both lines 10 and 15

You increment (count) in the loop header ..

1
2
   for (int count = 1; count <= 20; count++)       
 
Hi,

You are incrementing the count variable inside the for loop body - which isn't necessary - that is what the count++ on line 2 does. So remove lines 10 & 15.

Try not to have magic numbers in your code - like 20, make them const variables instead. That way if you have to change it, you only do it on one line, not throughout the code.

Hope all goes well :+)
Thanks for the tips! I guess I kind of confused for and while loops a bit when I was writing XD
Topic archived. No new replies allowed.