将除法结果四舍五入到c中的下一个整数



我编写代码显示多个页面(最多5行/页),其中包含一个列表中的人员:

/* PRE:     page : number of the page we want to show, starting with 1
 * RETURNS: pagenumber of the page showing if there is one, 0 otherwise  */

const int buf_length = 255;
const int max_num_lines = 15;
const int num_person_per_page = max_num_lines / 3;
const int num_person = person_get_num_person(personmgr);
char buf[buf_length+1];
int i, count, cur = 0;
/* List Header */ 
snprintf(buf, buf_length, "List of person on page (%d/%d)):", page, num_person/num_person_per_page);
list_set_text( list, cur++, buf);
list_set_hilight(list, -1); 

如果列表中的人数不是5的倍数(在我的例子中是72),则最后一页的列表标题将返回页面总数为14,而不是15(14/15)。

首页列表标题:

List of person on page: 1/14:
01. AAA
02. BBB
03. CCC
04. DDD
05. EEE

第二页列表标题:

List of person on page: 2/14:
06. FFF
07. GGG
08. HHH
........................

最后一页列表标题:

List of person on page: 14/15:
71. XXX
72. ZZZ     

我想要一个四舍五入到下一个整数(页码要正确显示)。

72 / 5 = 14.4 => 15
70 / 5 = 14   => 14
36 / 5 = 7.2  => 8

首页列表标题:

List of person on page: 1/15:
01. AAA
02. BBB
03. CCC
04. DDD
05. EEE

第二页列表标题:

List of person on page: 2/15:
06. FFF
07. GGG
08. HHH
........................

最后一页列表标题:

List of person on page: 15/15:
71. XXX
72. ZZZ

您可以编写(n + 4) / 5来整体计算n  5:如果n已经是5的倍数,则添加4 / 5 == 0,否则添加1

包含math.h文件并使用其ceil()函数。

另一种方法:

(num_person/num_person_per_page) + ((num_person % num_person_per_page) ? 1 : 0);

也许可以理解一点。如果模量不为零,则加1。

最新更新