开发者

How to round down a double to the nearest smaller int in C?

I've got a double:

double d = 25.342;

How can I convert it to 25 value?

If it were -12.46 I'd like to get开发者_运维技巧 -13.


int i = (int)floor(25.342);


int i = (int)floor(25.342);

Note this will convert 12.99999 to 12.

Ref:

http://www.codecogs.com/reference/c/math.h/floor.php


Where x is your 25.342

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


#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;
}

You may also want to take a look at stdint.h

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜