To write numbers on the screen using the programming language C should be used functions printf and sprintf in order to convert number to sequence of characters.
C++ introduces streams and cout to print any kind of data.
How to Print Numbers with cout
Scientific notation is also called standard form or exponential notation. It is used to represent number that are too large or small to be written with decimal notation.
Number using scientific notation should be presented regarding the following formula:
To force cout to print numbers with scientific notation use scientific of namespace std.
In order not to use scientific notation for presentation of the numbers fixed of namespace std should be used.
Working with variables of floating-point type (float, double, etc.) may require specific precision of the output.
Use function precesion to get or set the precision of cout. An argument of type streamsize must be passed to the function to set a new value for the floating-point precision.
The field width determines the minimum number of characters to be printed. If the length of the text is shorted than the field width then text will be filled with specific character.
The character can be set using setfill. By default the character is a space. Call setw to set field width and ios_base::width to get the current field width.
int main(int argc, char** argv)
float nVar = 10.95;
//standart output as dec
std::cout << nVar << std::endl;
//number with leading spaces if number of characters is less than 10
std::cout << std::setw(10) << nVar << std::endl;
std::cout << std::scientific << nVar << std::endl;
//Precision is set to 0, so the value of nVar will be printed as 11
std::cout << std::fixed << nVar << std::endl;
[leon@localhost couttest]$ g++ main.cpp -Wall -o couttest
[leon@localhost couttest]$ ./couttest
Standard output stream
Get/Set floating-point decimal precision
Set field width
Set fill character
Use fixed-point notation
Use scientific notation