如何在 C 中将 double 向下舍入到最接近的较小整数?

问题描述 投票:0回答:4

我有一个

double

double d = 25.342;

如何将其转换为

25

如果是

-12.46
我想得到
-13
.

c integer double rounding
4个回答
33
投票
int i = (int)floor(25.342);

16
投票
int i = (int)floor(25.342);

注意这会将 12.99999 转换为 12.

参考


1
投票

你的

x
在哪里
25.342

int i = x >= 0 ? (int)(x+0.5) : (int)(x-0.5)

0
投票
#include <math.h>
#include <stdio.h>

int main(){

    double d = 25.342;
    double e = -12.99;

    printf("%d\n",(int)round(d)); // 25
    printf("%d\n",(int)round(e)); // -13

    return 0;
}

您可能还想看看 stdint.h

© www.soinside.com 2019 - 2024. All rights reserved.