利用C++ ceil()函数解决实际编程问题

1949idc 2年前 (2024-09-19) 阅读数 291 #编程语言

ceil() 函数是 C++ 标准库 <cmath> 中的一个函数,用于计算大于或等于给定浮点数的最小整数

  1. 计算某个数的上界:
#include<iostream>
#include <cmath>

int main() {
    double num = 5.6;
    int upper_bound = std::ceil(num);
    std::cout << "Upper bound of "<< num << " is: "<< upper_bound<< std::endl;
    return 0;
}
  1. 计算两个数之间的差值的上界:
#include<iostream>
#include <cmath>

int main() {
    double num1 = 7.3;
    double num2 = 2.8;
    double difference = num1 - num2;
    int upper_bound = std::ceil(difference);
    std::cout << "Upper bound of the difference between "<< num1 << " and "<< num2 << " is: "<< upper_bound<< std::endl;
    return 0;
}
  1. 在分页应用中,根据每页显示的项目数和总项目数计算总页数:
#include<iostream>
#include <cmath>

int main() {
    int total_items = 45;
    int items_per_page = 10;
    int total_pages = std::ceil(static_cast<double>(total_items) / items_per_page);
    std::cout << "Total pages: "<< total_pages<< std::endl;
    return 0;
}

这些示例展示了如何使用 ceil() 函数解决实际编程问题。请注意,在使用 ceil() 函数时,确保包含 <cmath> 头文件。

版权声明

本文内容由互联网用户自发贡献,该文观点仅代表作者本人
本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

© 2010 首途云安 & 厦门硕顿信息技术有限公司 & 闽ICP备11016866号  增值电信业务经营许可证:B1-20203020 地址:福建厦门思明区嘉禾路297号1806
高新技术企业
软件产品证书
计算机软件著作权
ISO认证
国家3A企业