请问C语言(C++)怎么向上取整啊?

img


请问C语言(C++)怎么向上取整啊?例如7/2 = 4尝试过ceil,但是运行错误

floor函数
向下取整。floor(x)返回的是x的整数部分。如: floor(2.5) = 2 floor(-2.5) = -3

ceil函数
向上取整。ceil(x)返回的是不大于x的最小整数。如: ceil(2.5) = 3 ceil(-2.5) = -2 floor和ceil对于正数没有区别,但是对于负数结果不同。floor()是向负无穷大舍入,floor(-2.5) = -3;ceil()是向正无穷大舍入,ceil(-2.5) = -2。
代码修改如下:

#include <iostream>
using namespace std;
int main()
{
    int n,x,y;
    cin >> n>>x>>y;
    //因为n,x,y都是整数,所以y/x会把小数丢掉,
    //假如y=3,x=2,y/x的值是1,而不是1.5,需要对x或者y或者n做类型转换
    int z = ceil(n-(double)y/x); //此处对y做类型转换
    cout<<z<<endl;
    return 0;
}

ceil又不是数据类型,是函数,你这么写怎么可能

供参考:

// C++:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
    int n,x,y;
    cin>>n>>x>>y;
    double z;
    z = ceil((long double)(n-x)/y);
    cout<<z<<endl;
    
    return 0;

// C :
#include<stdio.h>
#include<math.h>
int main()
{
    int n,x,y;
    scanf("%d%d%d",&n,&x,&y);
    int z = ceil((double)(n-x)/y);
    printf("%d\n",z);
   
    return 0;
}

在C语言以及前端的less和sass中,使用ceil()和floor()函数时,其中传入的必须是确定的数值,不能是变量互相计算的结果,否则会出错。如果要使用变量,看我帖子