【发布时间】:2014-09-29 01:00:00
【问题描述】:
用户输入这样的双精度值:2423242.6789。只扫描 2423242 怎么办?
【问题讨论】:
-
为什么不直接读取浮点数然后转换为 int?
-
我已经尝试过 (int) x,但它似乎不起作用
-
“它似乎不起作用”是什么意思?你做了什么,你期望结果是什么?演员是如何未能达到这些期望的?
用户输入这样的双精度值:2423242.6789。只扫描 2423242 怎么办?
【问题讨论】:
假设一个正数,使用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
【讨论】:
%lf 扫描double 或将jdn 声明为float。
scanf("%lf", &jdn); (加l) 2) lc, nc,jc,day 是什么类型? 3) 输入是什么?
一种方法是使用整数说明符,例如
unsigned long long x;
if ( 1 != scanf( "%llu", &x ) )
// error handling...
但是,如果输入不适合 x,则会导致未定义的行为。
更可靠的方法是将字符读入缓冲区(例如通过fgets),然后使用strtoul 转换为整数。
【讨论】: