views:

274

answers:

8

How to get he upper limit of a number in C?

If I divide 3 by 2 I want the answer to be 2 (ie 1.5 rounded to 2).

+3  A: 

ceil(number)

Itay Moav
+3  A: 
#include <math.h>
ceil(3.0/2); //2.0

Note that one the operands should be double(or float) because 3/2 gives you 1

Lombo
Are you sure `2/3.0` == `2.0`?
thinkswan
Sorry my bad, thanks for the comment :P
Lombo
+2  A: 
int x= ceil((float)3/2);
aJ
+1  A: 

To round without using functions, just add half of the divisor before you divide. if the divisor is a constant, the compiler with optimize the code nicely.

int  number = 3;
int  divisor = 2;
int  result = (number + (divisor+1)/2) / divisor;
John Knoeller
+13  A: 

If you are just interested in dividing by 2, then just take (n + 1) / 2 to keep it in integer math. For example (3 + 1) / 2 gives 2. For a larger number x, use x - 1. For example, (3 + 7) / 8 = 1, for 3 divided by 8.

For the general case, you are looking for the ceiling function -- ceil. A quick Google search for "math ceil C" gave this page at the top of the results: http://www.elook.org/programming/c/ceil.html

Jim Flood
A: 
int i = 3;
int j = 2;
int k = (i + j - 1) / j;
Jonathan Leffler
A: 
int x = 3.0/2 + 0.5;
wilhelmtell
OP is asking for the ceiling function, not the round function. I too thought of this until I realized he *always* wants the next greatest integer regardless of th evalue.
Computer Guru
Ah. That wasn't entirely clear for me. He does use the word "rounded to.." :s
wilhelmtell
A: 

(If this qualifies as thread necromancy, kindly notify and I'll delete this)

A quick way to return an upward-rounded quotient is to add the divisor, minus one, to the dividend, and divide.

int ceil_div(int dividend, int divisor) {
    return (dividend + divisor - 1) / divisor;
}

or alternatively,

int ceil_div(int dividend, int divisor) {
    return (dividend - 1) / divisor + 1;
}

Consequentially, you'll work by subtracting 1 from 3, dividing by 2, and adding 1.

I'll try and explain why this works. If dividend and divisor were both floats, then the truncated integer equivalent of (dividend/*divisor*) would be equal to the ceiling of the quotient if divisor perfectly divides dividend, or one less if it does not perfectly divide dividend. By subtracting 1, we guarantee that the new dividend, dividend - 1, when divided by divisor, will always return a value lesser than the ceiling of the floating point quotient.

All that remains now is adding 1 to this quotient, which, incidentally, is floor((float) dividend / (float) divisor).

susmits