Eternal Learner
Eternal Learner

Reputation: 3870

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

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).

Upvotes: 2

Views: 4048

Answers (8)

susmits
susmits

Reputation: 2238

(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).

Upvotes: 1

wilhelmtell
wilhelmtell

Reputation: 58685

int x = 3.0/2 + 0.5;

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 754280

int i = 3;
int j = 2;
int k = (i + j - 1) / j;

Upvotes: 1

Jim Flood
Jim Flood

Reputation: 8477

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

Upvotes: 11

John Knoeller
John Knoeller

Reputation: 34148

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;

Upvotes: 1

aJ.
aJ.

Reputation: 35460

int x= ceil((float)3/2);

Upvotes: 2

Lombo
Lombo

Reputation: 12235

#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

Upvotes: 3

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53607

ceil(number)

Upvotes: 4

Related Questions