简体   繁体   English

需要帮助了解如何在C ++中使用round函数

[英]Need help understanding how to use the round function in C++

#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. 每当我运行我的代码时,它都能正确编译并为我提供正确的总体总数,但是round函数似乎无法正常工作。 I input 12 dollars for the meal total, 8 percent tip, and 20 percent tax. 我总共输入了12美元的餐费,8%的小费和20%的税。 The correct answer is $15.36, but I'd like to round it down to $15. 正确答案是$ 15.36,但我想将其四舍五入到$ 15。 Any help would be appreciated thanks. 任何帮助,将不胜感激谢谢。

You must assign the return value of the round() function to overall_total , like this: 您必须将round()函数的返回值分配给overall_total ,如下所示:

overall_total = round(overall_total);

The above line should replace round (overall_total); 上一行应替换为round (overall_total); .

Some functions in C++ take a reference (pass-by-reference) to the parameters of the function, eg 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. C ++中的某些函数对函数的参数进行引用(通过引用),例如std::sort() ,因此您只需std::sort(v.begin(), v.end())并且对向量v进行排序而无需分配返回值。 (Technically, std::sort takes in iterators which have similarities to pointers, but they basically have the same result.) (从技术上讲, std::sort引入了与指针相似的迭代器,但它们的结果基本相同。)

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. 但是, round()函数实际上会获取参数的副本(按值传递)并返回新值-它不会直接“重新分配”参数以具有取整值。 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? 按引用传递与按值传递有什么区别?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM