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

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

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

+3
source share
8 answers

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

- ceil. Google "math ceil C" : http://www.elook.org/programming/c/ceil.html

+13
#include <math.h>
ceil(3.0/2); //2.0

, double ( float), 3/2 1

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

, . , .

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

( , , )

- , , .

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

, ,

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

, 1 3, 2 1.

, . , (/) , , , . 1, , , -1 , , , .

, , 1 , , , ((float) divend/(float)).

+1
int x = 3.0/2 + 0.5;
0

Source: https://habr.com/ru/post/1737781/


All Articles