如何在小数点后截断值

时间:2014-09-29 01:00:01

标签: c truncate

用户输入如下的double值:2423242.6789。我该怎么办才能扫描2423242?

2 个答案:

答案 0 :(得分:1)

假设为正数,请使用floor()

#include <math.h> 

double x;
scanf("%lf", &x);
x = floor(x);
// or 
x = x < 0.0 ? ceil(x) : floor(x); // to cope with + and - doubles

答案 1 :(得分:0)

一种方法是使用整数说明符,例如

unsigned long long x;
if ( 1 != scanf( "%llu", &x ) )
      // error handling...

但是,如果输入不适合x,则会导致未定义的行为。

更可靠的方法是将字符读入缓冲区(例如通过fgets),然后使用strtoul转换为整数。

相关问题