Looking to round the final answer to 2 decimals C++

余生长醉 提交于 2020-01-25 05:07:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!