我讓代碼從一個列表中顯示多個頁面與個人(最多5條/頁。):四捨五入結果到下一個整數在C
/* 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);
如果列表中有人員巫ISN的數量是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
對我來說,@ Kerrek的方式更容易理解。但是,我很奇怪,所以也爲此+1。 – 2012-01-16 15:32:35
我也是這樣做的,但是最近在我的答案中提醒了方法,它基本上是一樣的:添加的「'4/5」的結果對另一方的其餘部分是「有條件的」如果你願意的話。它只是彙集成一個。或者,如果您願意,'+ 4'將「floor」更改爲「ceiling」。 – 2012-01-16 15:38:53
@Kerrek @我也喜歡你的方式,如果我有一個性能關鍵的代碼片段,我可能會偷它,因爲它會快得多(在真實世界的情況下1個額外的加法和1個額外的減法,而不是)但是我的「同伴」並不總是最多的,所以如果我在它自己的函數之外使用它,我可能不得不添加註釋來解釋它的作用,或者我肯定不得不在代碼審查過程中大聲地解釋它;) – Gerald 2012-01-16 15:58:46