开发者

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 开发者_C百科I divide 3 by 2 I want the answer to be 2 (ie 1.5 rounded to 2).


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


ceil(number)


#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


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


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;


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


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


int x = 3.0/2 + 0.5;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜