#include<iostream>
#include<iomanip>
#include<string>
 
using namespace std;
 
int main() {
 
	cout << "\tPI:\n\n";
	// PI
	const double PI = 3.14159; // approximately
	// I use this sometimes: const double PI = 4.0*atan(1.0);
	cout << "PI is " << PI << endl;
 
 
	// Formatting role play, then
	cout << endl << "\tFORMATTING:\n\n";
	double aCoolNumber = PI;
	int anotherCoolNumber = 7;
	cout << "The way it comes out by default: " << aCoolNumber << endl;
	// we can change that: (note #include of iomanip!)
	cout << "The way it comes out modified by fixed and setprecision: " << fixed << setprecision(3) << aCoolNumber << endl;
	cout << "The way it comes out modified by fixed and setprecision (rounding!): " << fixed << setprecision(4) << aCoolNumber << endl;
	cout << "We round the output but not the value itself: " << fixed << setprecision(5) << aCoolNumber << endl;
	cout << "The way it comes out modified by setw too small (*10000 to make it big): " << setw(3) << aCoolNumber*10000 << endl;
	cout << "The way it comes out modified by setw more than big enough: " << setw(13) << aCoolNumber << endl;
	cout << "The way it comes out modified by setw but only affect next item: " << setw(13) << anotherCoolNumber << " and " << aCoolNumber << endl;
	cout << "The way it comes out modified by setw on both items: " << setw(13) << anotherCoolNumber << " and " << setw(13) << aCoolNumber << endl;
	cout << "The way it comes out enlarging the precision: " << fixed << setprecision(8) << aCoolNumber << endl;
 
	cout << endl << "\tROUNDING:\n\n";
 
	// from last time: c++ does not round
	double priceOfCar = 12345.53;
	int roundedPrice = priceOfCar;
	cout << "price " << priceOfCar << " or rounded is " << roundedPrice << " dollars??\n";
	// but you can make it round:
	roundedPrice = priceOfCar + 0.5;
	cout << "price " << priceOfCar << " or rounded is " << roundedPrice << " dollars.\n";
	// rounded to the nearest 100
	cout << "price " << priceOfCar << " or rounded to the nearest 100 is " << 100*(static_cast<int>(priceOfCar/100+0.5)) << " dollars.\n"; // is / ok?
        cout << endl;
 
	//system("pause");
	return 0;
}
cs-142/formatting.txt · Last modified: 2016/09/06 16:24 by kseppi
Back to top
CC Attribution-Share Alike 4.0 International
chimeric.de = chi`s home Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0