Milan
Milan

Reputation: 205

Percentages in calculation

I wrote this code:

std::cout << "When did you graduate? "; 
int graduation_year = 0;
std::cin >> graduation_year;
std::cout << "\n"; 
std::cout << "How much is your student debt? ";
double debt = 0;
std::cin >> debt;

std::cout << "You graduated in " << graduation_year << " and have student debt worth " << debt << ".\n";

double discount = 0;

switch (graduation_year) {
case 2010:
{
    if (debt >= 5000 && debt < 10000)
        double discount = .99;
    double payment = debt * discount;
    std::cout << "Your student debt is between 5000 and 10000 which means your payment would be " << payment << "\n";
}
break;

This is not for a school assignment, I'm simply trying to learn C++ and trying to get the hang of percentages and switch/case.

Annoyingly, when I change this part

    double discount = .99;
double payment = debt * discount;

to

double payment = debt * 0.99;

it works perfectly. So I feel like something might be going wrong because of the double being <1, but I can't for the life of me figure out what it is. The code continues with case 2011 etc, but it gives the exact same problems for that part of the code so I figured I'd leave that out.

Upvotes: 5

Views: 207

Answers (1)

Patrick Trentin
Patrick Trentin

Reputation: 7342

You are re-declaring discount as an internal variable to the block of the following if-statement

if (debt >= 5000 && debt < 10000)
    double discount = .99;

You should write it like this:

if (debt >= 5000 && debt < 10000)
    discount = .99;

ETA: a bit of explanation.

The discount declaration within the if-block temporarily hides the global discount declaration. Although the value is correctly assigned to the inner discount declaration, when you get out of the if-block this variable is out of scope, and any further reference to discount is resolved using the global discount declaration. Since you didn't change the global variable, you don't get the right result.

Upvotes: 12

Related Questions