Some newbie casting issues

S

SabaUd

Hello,
I wrote a short program that needs to calculate capacity of stack.
i have 2 ints and im trying to do so.
my code:

Stack* selectedStack = ...;
double fActual = (double)selectedStack->nActualSize;
double fAllocated = (double)selectedStack->nAllocatedSize;
double fCapacity = (fActual / fAllocated) * 100.0;
printf("%d ", (int)ceil(fCapacity));

Now - this one works, but it's disgusting code...

I'm sure there's a more elegant way to execute it...

any ideas?
 
R

Richard Heathfield

SabaUd said:
oh, another one I forgot:
I want to print "30%"...
how do I print '%'?

See page 13 of "The C Programming Language", 2nd edition, by Kernighan and
Ritchie.
 
S

santosh

SabaUd said:
Hello,
I wrote a short program that needs to calculate capacity of stack.
i have 2 ints and im trying to do so.
my code:

Stack* selectedStack = ...;
double fActual = (double)selectedStack->nActualSize;
double fAllocated = (double)selectedStack->nAllocatedSize;
double fCapacity = (fActual / fAllocated) * 100.0;
printf("%d ", (int)ceil(fCapacity));

Now - this one works, but it's disgusting code...

I'm sure there's a more elegant way to execute it...

any ideas?

Yes. Provide separate functions that take a Stack * argument and return
details (like capacity, size etc.) about it. And consider using size_t
as the object type for returning size and capacity related values,
since that is the natural type for such purposes in Standard C.
 
M

Minimiscience

SabaUd said:
Hello,
I wrote a short program that needs to calculate capacity of stack.
i have 2 ints and im trying to do so.
my code:

Stack* selectedStack = ...;
double fActual = (double)selectedStack->nActualSize;
double fAllocated = (double)selectedStack->nAllocatedSize;

These two casts aren't actually needed, unless you're using a very strict
compiler or you're compiling this as C++ code.
double fCapacity = (fActual / fAllocated) * 100.0;
printf("%d ", (int)ceil(fCapacity));

This cast, however, is needed so that printf() is passed the right type of
value.
 
P

Peter Nilsson

SabaUd said:
I wrote a short program that needs to calculate capacity
of stack.
i have 2 ints and im trying to do so.
my code:

Stack* selectedStack = ...;
double fActual = (double)selectedStack->nActualSize;
double fAllocated = (double)selectedStack->nAllocatedSize;
double fCapacity = (fActual / fAllocated) * 100.0;
printf("%d ", (int)ceil(fCapacity));

Now - this one works, but it's disgusting code...

Assuming nXXXXX are indeed integers...

printf("%3.0f%%\n", 100.0 * selectedStack->nActualSize
/ selectedStack->nAllocatedSize);
 

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,046
Latest member
Gavizuho

Latest Threads

Top