-1
#include <iostream>
#include <iomanip>
#include <cmath>

using namespace std;

int main () {

//initializing my variables
double mealcost;
float tax_percent, tip_percent, tax_total, tip_total, overall_total;

cout << "What is the cost of your meal?" << endl;
cin >> mealcost;

cout << "What percent tip would you like to leave?" << endl;
cin >> tip_percent;

cout << "What percent are you taxed?" << endl;
cin >> tax_percent;

tax_total = mealcost * (tax_percent/100);
tip_total = mealcost * (tip_percent/100);
overall_total = mealcost + tax_total + tip_total;


/*trying to take the overall total from the formula above and round it
to the nearest whole integer*/



round (overall_total);

cout << "What is the total cost of my meal? " << overall_total << endl;


return 0;
}

Whenever I run my code it compiles correctly and gives me the correct overall total, but the round function seems to not work. I input 12 dollars for the meal total, 8 percent tip, and 20 percent tax. The correct answer is $15.36, but I'd like to round it down to $15. Any help would be appreciated thanks.

1 Answers1

4

You must assign the return value of the round() function to overall_total, like this:

overall_total = round(overall_total);

The above line should replace round (overall_total);.

Some functions in C++ take a reference (pass-by-reference) to the parameters of the function, e.g. std::sort(), so that you simply std::sort(v.begin(), v.end()) and the vector v is sorted without you having to assign the return value. (Technically, std::sort takes in iterators which have similarities to pointers, but they basically have the same result.)

However, the round() function actually takes a copy (pass-by-value) of the parameter and returns a new value - it does not directly 're-assign' the parameter to have the rounded value. Therefore, you must assign the return value of the function to a variable (or in this case, the same variable in order to 're-assign').

You can learn more about the difference here:

What's the difference between passing by reference vs. passing by value?

RealPawPaw
  • 988
  • 5
  • 9
  • [Documentation link for `std::round` and family](https://en.cppreference.com/w/cpp/numeric/math/round) Note you may have to turn on C++11 (or better) Standard support. – user4581301 Feb 01 '19 at 23:17
  • okay, I tried it for some reason I keep getting the same answer. I initialized it at the top like this... float overall_total = round (overall_total); – Andy Mercado Feb 01 '19 at 23:19
  • 1
    You don't initialise it at the top because otherwise it'll round an undefined value! You should replace the line above where you print the answer with the example I have provided. – RealPawPaw Feb 01 '19 at 23:21