Rounding to next highest number?

N

NoKetch

I have a simple program to output log2(x) but the result is not whole numbers.
Here is the code:

----------------------
#include <stdio.h>
#include <math.h>

int main()
{
double x;

printf("Enter a Number: ");
scanf( "%lf", &x);

if ( x >= 0 )
printf("\nResult: %lf\n", log2(x));

system("PAUSE");
return 0;
}
----------------------

I get results like this:

Result: 4.321928
Result: 5.459432

How do i round these numbers to the next highest whole number so that the
output would be:

Result: 5
Result: 6

I'm not a very experienced programmer, so the explanation should be fairly
simple. :)

Thanks for any tips


Dave
 
C

Christopher Benson-Manica

NoKetch said:
How do i round these numbers to the next highest whole number so that the
output would be:

Use ceil(), from the math library. #include math.h and do whatever
may be necessary on your system to link to the math library. Check
your friendly documentation or man page for more details.
 
T

Thomas Stegen

Mark said:
Or you could at 0.5 to the result and then cast to int. E.g.

(int) (4.732 + 0.5) is 5.

That depends on if you want to round away from zero or in a positive
direction. What you have rounds in a positive direction
 
M

Mark A. Odell

Rather than stew about what happens here, I think you should use ceil().
After all that IS what you want to do. Why make some other poor soul
figure out what you were up to? Eschew obfuscation!

I agree. On a small 8-bit micro, I might do this instead of ceil() if I
hadn't used any FP library functions anywhere else. Ceil() is the better
choice in most cases I would think.
 
O

osmium

Thomas said:
That depends on if you want to round away from zero or in a positive
direction. What you have rounds in a positive direction

Rather than stew about what happens here, I think you should use ceil().
After all that IS what you want to do. Why make some other poor soul figure
out what you were up to? Eschew obfuscation!
 
M

Mark McIntyre

I agree. On a small 8-bit micro, I might do this instead of ceil() if I
hadn't used any FP library functions anywhere else. Ceil() is the better
choice in most cases I would think.

ceil() can lead to unexpected results when reading in data from
external sources, due to FP inaccuracies. Well I reckon it always
surprises to see ceil(5.0f) == 6 anyway.
 

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,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top