'Why is this while loop returning this random values?
Although I'll explain, here is the exercise detailed. So what the code is supposed to do is grab a double and apply a fixed tax to it then display the total amount of tax. Everything bellow 2000.00 is not taxed everything from 2000.01 to 3000.00 will be taxed in 8%, 3000.01 to 4500.00 with 18% and everything above 4500.00 with 28%. Therefore, when the user enter 4520.00 (this example is in the link) the code should sum (0.28 * 20 + 0.18 * 1500 + 0.08 * 1000) which is 355.60.
My code works not in the easiest way because I'm learning and I try to think of alternative and or creative ways to make it work, so I used vectors with the while statement to make a loop. It works (or it should) by subtracting salario by the highest value (4500) from the const vector renda and if the amount is not negative it applies another const as the tax making a sum to the total tax value which starts at 0.0. Then it resets the value of salario because otherwise it would have applied the taxes only to what is above 4500 and then it repeats two times this time repeating a part of the previous loop as in the example of 4520.00 in the second loop it would subtract salario (4520) by 3000 which would leave 1520 but we can't apply taxes again to that 20 because we already have so we repeat the part of the previous loop that left 20 and subtract that as well, we do the same in the last loop.
The problem is that I don't have the slightest idea as to what is wrong in the code. When I enter 4520.00 it returns 606.00 for some reason and I don't see logic behind it. If anyone can help me on this I would pretty much appreciate it.
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main(){
const vector <int> renda {2000, 3000, 4500};
const vector <double> taxa {0.08, 0.18, 0.28};
double salario {};
double imposto {0.0};
int i {2};
cin >> salario;
const double salario_const = salario;
if (salario <= 2000.00)
cout << "Isento" << endl;
else {
while (i >= 0) {
if (i == 2)
salario -= renda.at(i);
else
salario -= renda.at(i) - (salario - renda.at(i+1));
if (salario > 0)
imposto += salario*taxa.at(i);
salario = salario_const;
i -= 1;
}
cout << setprecision(2) << fixed;
cout << "R$ " << imposto << endl;
}
return 0;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|