C语言分页功能实现代码示例
以下是用C语言实现分页功能的示例代码:
#include <stdio.h>
#define PAGE_SIZE 10
void displayPage(int page, int totalPages) {
int start = (page - 1) * PAGE_SIZE + 1;
int end = start + PAGE_SIZE - 1;
if (end > totalPages) {
end = totalPages;
}
printf('Displaying page %d of %d\n', page, totalPages);
for (int i = start; i <= end; i++) {
printf('Item %d\n', i);
}
}
int main() {
int numItems = 100;
int totalPages = (numItems + PAGE_SIZE - 1) / PAGE_SIZE;
int currentPage = 1;
displayPage(currentPage, totalPages);
char choice;
do {
printf('Enter 'n' for next page, 'p' for previous page, or 'q' to quit: ');
scanf(' %c', &choice);
switch (choice) {
case 'n':
if (currentPage < totalPages) {
currentPage++;
}
break;
case 'p':
if (currentPage > 1) {
currentPage--;
}
break;
}
displayPage(currentPage, totalPages);
} while (choice != 'q');
return 0;
}
这段代码使用了一个常量 PAGE_SIZE 来表示每页显示的项目数量。displayPage 函数根据当前页数和总页数计算出要显示的项目范围,并将其打印出来。
在 main 函数中,我们首先计算出总页数,然后初始化当前页数为 1,并显示第一页的内容。接下来,使用一个循环来读取用户的选择,根据选择来更新当前页数,并显示相应的内容,直到用户选择退出为止。
原文地址: https://www.cveoy.top/t/topic/qqRd 著作权归作者所有。请勿转载和采集!