formatting question

W

wongjoekmeu

Hello All,

I have a following piece of code in C that I need to rewrite to C++.
However I just don't seem to be able to understand the format rules in
C.

The C code look like this:

I have two doubles x and y which has a value. Now their values are
written to
output with printf in the following way.

printf("%1f %3.2e\n",x,y);

I have read in a book that for instance %5.4f means write the float
with 5 digit
widt where 4 digit are dedicated to the decimal portion. However why
can I then
print out values with more then one digit ????
Can anyone explain this to me ????
And then what does %3.2e means then ??
That I will get at most 3 digits ???
where 2 are dedicated to the decimal ???
How can I rewrite this to C++ using cout to write to output ??
Thank you in advance
 
V

Victor Bazarov

I have a following piece of code in C that I need to rewrite to C++.
However I just don't seem to be able to understand the format rules in
C.

The C code look like this:

I have two doubles x and y which has a value. Now their values are
written to
output with printf in the following way.

printf("%1f %3.2e\n",x,y);

I have read in a book that for instance %5.4f means write the float
with 5 digit
widt where 4 digit are dedicated to the decimal portion.

Kind of. 5 would be the width of the whole field and 4 is the decimal
digits after the dot. If the number doesn't fit in 5 symbols considering
leading digits (before the decimal point) and the sign and the dot itself,
then the width is ignored.
However why
can I then
print out values with more then one digit ????

Because the width is ignored if the number doesn't fit.
Can anyone explain this to me ????

Get a good book.
And then what does %3.2e means then ??

It means to print out in scientific format with two decimal digits after
the floating point. The width 3 is not going to be enough, so it will be
ignored.
That I will get at most 3 digits ???

No. You will get 2 digits after the dot.
where 2 are dedicated to the decimal ???
Yes.

How can I rewrite this to C++ using cout to write to output ??

Read about 'fixed' and 'scientific' manipulators and also 'setprecision'
and 'setw', although the latter is not that important.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,663
Latest member
josh5959

Latest Threads

Top