visual studio - How to properly set precision for doubles in C++ -
i'm working on project need math , give user output dollars in it, have console tell user answer $20.15 instead of $20.153. used set precision function such: cout << setprecision(2);, rather have numbers become want them be, converted scientific notation.
i'm outputting lot of numbers, having function setprecision best me ease of use.
how have numbers displayed 2 decimal places , not have console give me numbers in scientific notation?
thanks
nathan
edit:
here part of code i'm having problems with:
int main() { cout << setprecision(2); if (totalcosthybrid < totalcostnonhybrid) { cout << "hybrid car: " << endl; cout << "total cost: " << totalcosthybrid << endl; cout << "total gallons used: " << milesperyear / hybrideffic << endl; cout << "total gas cost: " << gascosthybrid << endl; cout << "non-hybrid car: " << endl; cout << "total cost: " << totalcostnonhybrid << endl; cout << "total gallons used: " << milesperyear / nonhybrideffic << endl; cout << "total gas cost: " << gascostnonhybrid << endl; cout << "hybrid cheaper!" << endl; } obviously there's more it, need with.
to fix that, should use fixed floating-point notation cout. can find more info here.
try addind cout << fixed code, code below. set precision 2, can use precision property.
cout << fixed; cout.precision(2); here complete code:
using namespace std; int main() { cout << fixed; cout.precision(2); if (totalcosthybrid < totalcostnonhybrid) { cout << "hybrid car: " << endl; cout << "total cost: " << totalcosthybrid << endl; cout << "total gallons used: " << milesperyear / hybrideffic << endl; cout << "total gas cost: " << gascosthybrid << endl; cout << "non-hybrid car: " << endl; cout << "total cost: " << totalcostnonhybrid << endl; cout << "total gallons used: " << milesperyear / nonhybrideffic << endl; cout << "total gas cost: " << gascostnonhybrid << endl; cout << "hybrid cheaper!" << endl; } }
Comments
Post a Comment