how to display 12345 as 12,345 ??

P

pembed2003

news.hku.hk said:
thanks for all of your's help
but i still can't grasp the idea of the algorithm
maybe could anyone explain in words(preferably with c++ codes) that how the
algorithm works ??
Thanks

My solution is very simple so I will try to explain it to you.

The first parameter v is the number that you want to display and will
always be positive (see below for reason). The second parameter n
tells the function whether the number v is negative to start with. It
will be true if it's. Otherwise, it will be false.

If v is greater or equal to 1000, we know we need to display comma.
The first comma comes in before the last three digits. The last three
digits are extract with:

int r = v % 1000;

So for example if v = 1234:

1234 % 1000 = 234

But we can't simply display 234 yet because it's the last three digits
which should displayed last. So we need to store this number somewhere
for later display. The way we store it is in the run time stack by
calling the same function again. But after extract the last three
digits, we have 1/1000 less of the number to work with so we call the
function again with:

_display_number(v / 1000,n);

So the stack grows up:

_display_number(1234,n): 1234 % 1000 = 234
_display_number(1234/1000,n): 1 % 1000 = 1

When the function finally finish (because 1 < 1000), the run time
stack is pop so we can properly display:

1,234


This simply ensure v is passed to _display_number as a positive number
and v < 0 will be true if v is negative and false otherwise.

If I use the terminology incorrectly, someone please correct me. But
basically that's how the algorithm works. HTH. Thanks!
 

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

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top