Question

for example im getting an area of 6 for a triangle, i need my output to show 006.000

i know setprecision will do the trick for limiting the decimal places to three but how do i place zeros in front of my solutions?

this is what i have

CTriangle Sides(3,4,5);

cout << std::fixed << std::setprecision(3);

cout << "\n\n\t\tThe perimeter of this tringle is   = " << Sides.Perimeter();

cout << "\n\n\t\tThe area of the triangle is        = " << Sides.Area();

cout << "\n\n\t\tThe angle one is                   = " << Sides.Angleone();

cout << "\n\n\t\tThe angle two is                   = " << Sides.Angletwo();

cout << "\n\n\t\tThe angle three is                 = " << Sides.Anglethree();

cout << "\n\n\t\tThe altitude one of the triangle   = " << Sides.Altitudeone();

cout << "\n\n\t\tThe altitude two of the triangle   = " << Sides.Altitudetwo();

cout << "\n\n\t\tThe altitude three of the triangle = " << Sides.Altitudethree();

with the output being

            The perimeter of this triangle is   = 12.000

            The area of the triangle is        = 6.000

            The angle one is                   = 90.000

            The angle two is                   = 36.870

            The angle three is                 = 53.130

            The altitude one of the triangle   = 2.400

            The altitude two of the triangle   = 6.667

            The altitude three of the triangle = 3.750

but i need all the answers to be in this form XXX.XXX regardless of what my solutions are.(because the values will change)

any help is appreciated, thanks!

Était-ce utile?

La solution

Use can use padding and filling manipulators:

std::setfill('0');             // is persistent
//...

cout << std::setw(7) << value; // required for each output

Autres conseils

Using std::internal, std::fixed, std::setfill, std::setw and std::setprecision from iomanip and related headers, you can do:

std::cout << std::fixed << std::setfill('0') << std::internal << std::setprecision(3);

std::cout << std::setw(7);
std::cout << 12.34f << "\n";

and get the desired output. See it live on Coliru!

The printf function can do that for you have a look at the docs: http://www.cplusplus.com/reference/cstdio/printf/

Your case is somewhat unique because: (these are not complete code snippets, apologies)

precision only applies to floating point formatting:

$ printf("%03.3f\n", 6)
> 6.000

And left padding only applies to integer formatting:

$ printf("%03.3d\n", 6)
> 006

Good luck hopefully you can take it from here

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top