-2

C++ question- "Write a program that will calculate total savings by a student with his/her parents’ contribution. The student’s parents have agreed to add to the student’s savings based the percentage the student saved using the schedule given below" This is the if/else if I used to find out the parents contribution. I now have to make this program again except with a switch statement. I don't know exactly how to do that. The user inputs total earnings, and amount he decided to put away. (My course just started so I have to use very simple processes to do this thank you) Here's the first version:

percent_saved = money_saved / money_earned;          // calculates the percent of how much was saved

if (percent_saved <.05)                              // this if/else if statement assigns the parents percentage of contribution to their students saving
{
    parents = .01;
}
else if (percent_saved >= .05 && percent_saved < .1)
{
    parents = .025;
}
else if (percent_saved >= .1 && percent_saved < .15)
{
    parents = .08;
}
else if (percent_saved >= .15 && percent_saved < .25)
{
    parents = .125;
}
else if (percent_saved >= .25 && percent_saved < .35)
{
    parents = .15;
}
else
{
    parents = .2;
}

parentsmoney = parents*money_earned;                 // using the correct percentage, this creates the amount of money parents will contribute
total_savings = parentsmoney + money_saved;          // this adds together the parent's contribution and the student's savings 

1 Answers1

3

This can't (shouldn't) be done in this case: switch is only useful for discrete integer values. It is not useful for non-trivial ranges and cannot be used directly with floats.

Anyway, about half the conditionals can be removed from the if-expressions if the ordering reversed such that the tests are inchworm'ed through..

if (percent_saved >= .35) {
    parents = .2;
} else if (percent_saved >= .25) {
    parents = .15;
} // etc.

Now, if the requirement is to "use a switch statement" (silly homework problems), then consider first normalizing the floating value into "buckets" such that 0.05 => 1, 0.1 => 2, 0.15 => 3, etc. The resulting integer can then be checked in a relevant case (with some cases being fall-throughs), as shown in the linked question..

int bucket = rint(percent_saved / 0.05);
Community
  • 1
  • 1
user2864740
  • 60,010
  • 15
  • 145
  • 220