Problems with a for loop

Sep 24, 2014 at 2:49pm
Hello, I'm trying to create a program that makes the user enter a start value, an end value, the amount the value should increase after each loop and some calculations should be printed out to the user.

Example:

User Input:
First price: 10.00
Last Price: 15.00
Amount to add every time: 0.5
Vatpercentage: 10

Output:
1
2
3
4
5
6
7
=== Vat Table ===
Price without Vat   Vat  Price with vat
           10.00    1.00          11.00
           10.50    1.05          11.55
           11.00    1.10          12.10
           .....    ....          .....
           15.00    1.50          16.50


The dots are the rest of the output. From the code I have now I only get an endless loop of 10.00 and it never leaves the loop. What am I doing wrong?

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
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
  float first = 0, last = 0, amount = 0, vat = 0, total = 0, vattotal = 0;

  cout << "First price: ";
  cin >> first;

  cout << "Last price: ";
  cin >> last;

  cout << "Amount to add every time: ";
  cin >> amount;

  cout << "Vatpercent: ";
  cin >> vat;

  vat = vat / 100;
  total = (vat * first) + first;

  cout << "=== Vat Table ===" << endl;
  cout << "Price without vat " << " Vat " << " Price with vat" << endl;
 
  for(int i = first; first < last; i +=amount)
    {
      cout << setprecision(2) << fixed << i << "   " << vat << "   " << total << endl;
    }
 
  return 0;
}
Last edited on Sep 24, 2014 at 2:51pm
Sep 24, 2014 at 3:04pm
for(int i = first; first < last; i +=amount)

I think you meant to put i < last ? If first is less than last, the condition you have now will always be true - creating an infinite loop.

cout << setprecision(2) << fixed << i << " " << vat << " " << total << endl;

total isn't getting recalculated in the loop so it will have whatever value it was assigned on line 22. edit: also vat looks like it should be recalculated.
Last edited on Sep 24, 2014 at 3:07pm
Sep 26, 2014 at 11:51am
Yes it should me i < last and i should be asigned as a float not an int that was what was causing me the most trouble. I solved it after some deep analyse of the code, thanks for the help though!
Topic archived. No new replies allowed.