我有一个
如何将其转换为25?
如果是-12.46,我想要得到-13。
double
:double d = 25.342;
如何将其转换为25?
如果是-12.46,我想要得到-13。
int i = (int)floor(25.342);
(int)floor(-25.342)
返回 -26,而 (int) -25.342
返回 -25。如果您知道值为正,则不需要使用 floor
。 - yellowantphilint i = (dbl >= 0 ? (int) dbl : ((int) dbl) -1;
@amarillo - Aaron Campbelldbl
是一个负整数时,((int) dbl) -1
就无法正常工作。 - chux - Reinstate Monicafloor( )
返回一个 double 值(C标准 §7.12.9.2)。 - Stephen Canon其中x
是你的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;
}
你可能也想看一下 stdint.h
25.9
),该方法失败,因为它不能“将double舍入到最接近的较小整数”。 - chux - Reinstate Monica
floor()
返回一个非整数值,那么这是一个 bug ,你应该向提供该系统上的数学库的人抱怨。 - Stephen Canon