问题
I'm trying to round my final answer to 2 decimals so it is Dollars and Cents. I'm new to coding, and can't figure it out. I want to round "w" in the line that says "The amount you need to charge is" Here's my code:
#include <iostream>
using namespace std;
int main()
{
string Choice;
float x, w;
cout << "Please enter the amount needed." << endl;
cin >> x;
w = x/(1-0.0275);
cout << "The amount you need to charge is $"<< w << "." << endl;
return (0);
}
回答1:
According to the example here http://www.cplusplus.com/forum/beginner/3600/ You could use
cout << setprecision(2) << fixed << w << endl;
(fixed
is optional)
You will have to #include <iomanip>
As pointed out by Synxis, this will only work for printing the value, it will not change the value held by w
回答2:
You can alway multiply your answer x
by 100, round, and then divide by 100.
x = (int)(x*100+0.5f);
x = ( (float)(x) ) / 100.0;
回答3:
You could change your monetary unit to "cents" and then divide by 100 to get the dollars and mod 100 to get the cents.
unsigned int money = 152; // USD $1.52
cout << "Money is: " << (money / 100) << "." << (money % 100) << "\n";
This may be more accurate. Search the web for "everything knows floating point".
来源:https://stackoverflow.com/questions/15189084/looking-to-round-the-final-answer-to-2-decimals-c