c - fscanf 不能正确读取双精度
问题描述
我有一个功能
void getXFromFile3(FILE* fptr){
double valueX;
fscanf(fptr, "%lf\n", &valueX);
printf("%lf", valueX);
}
和文件 data.dat 一些双数。
其中之一是-0.572869279
,但我的功能 print -0.572869
。看来我的号码在某个地方被切断了。
任何想法我做错了什么?
解决方案
告诉scanf
你它扫描了多少个字符,然后告诉你printf
在逗号后打印这个数字。
仍然需要注意逗号前的符号和数字。
下面的代码假定前导零并且输入中没有正号。
void getXFromFile3(FILE* fptr){
double x;
int n;
fscanf(fptr, "%lf%n", &x, &n);
printf("%.*lf", /* the l length modifier is optional */
n /* number of characters scanned */
- (x < 0.) /* one off for the minus sign, if any */
- ((int)log10(fabs(x)) + 1) /* off as many as digits before the comma */
- 1, /* one off for the comma */
x);
}
胡!;-)
推荐阅读
- assembly - 与 BNE 执行和标签指令获取相关的流水线停顿
- azure-stream-analytics - 流分析 UDF - 在另一个 UDF 中使用一个 UDF 的输出
- java - 如何在android中按字符串值过滤json对象?
- laravel - Htaccess Laravel - 删除公用文件夹 URL
- jquery - 我希望我的 setTimeout 函数在单击期间立即再次按下它时重新启动
- android - 在 android Kotlin 中绘制螺旋视图
- regex - 包含斜杠和星号作为常量的正则表达式
- python - 用字符串数字键对字典进行数字排序的最 Pythonic 方法是什么?
- c - 为什么分段错误和程序以退出代码 139 结束?
- apache-spark - 来自 Kafka 的 Spark DStream 总是从头开始