fscanf 没有正确读取浮点数 [英] fscanf not reading floats correctly

查看:105
本文介绍了fscanf 没有正确读取浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

---这是一个家庭作业问题---

---This is a Homework question---

我在使用 fscanf 从文本文件中读取浮点值时遇到问题.

I'm having problems reading float values from a text file using fscanf.

基本上我试图从文件中读取浮点值并将它们存储在动态数组中.输入文件每行有两个浮点数.所以一行可能是0.85 7.34"(不带引号).所以我试图使用 fscanf(fp, "%f %f", &coordinates[i], &coordinates[i++]) 来读入 2 个浮点值.当我打印时它显示为 0.00000.下面是我写的代码和它产生的输出.

Basically I'm trying to read float values from a file and store them in a dynamic array. The input file has two floats per line. so a line might be "0.85 7.34" (w/o quotes). so I'm trying to use fscanf(fp, "%f %f", &coordinates[i], &coordinates[i++]) to read in the 2 float values. when i print it shows as 0.00000. Below is the code I wrote and the output it produces.

#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv []) {

FILE * fp = fopen("nums", "r");

float *coordinates;
float *tmp;
int i = 0;
int ARRAY_SIZE = 5;
coordinates = malloc(5*sizeof(float));

while (fscanf(fp,"%f %f", &coordinates[i], &coordinates[i++]) > 1)
{

  printf("iteration# %d | coord1 = %f coord2 = %f \n", i, &coordinates[i-1], &coordinates[i]);

  if (i >= ARRAY_SIZE)
  {
    tmp = realloc(coordinates, (i*2)*sizeof(float));
    coordinates = tmp;
    ARRAY_SIZE = i*2;
  }
  i++;
}

for(i = 0; i < 8; i++)
  printf("%f\n", &coordinates[i]);


return 0;
}

输出:

iteration# 1 | coord1 = 0.000000 coord2 = 0.000000 
iteration# 3 | coord1 = 0.000000 coord2 = 0.000000 
iteration# 5 | coord1 = 0.000000 coord2 = 0.000000 
iteration# 7 | coord1 = 0.000000 coord2 = 0.000000 
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000
0.000000  

推荐答案

您不要将地址"-运算符 &printf 一起使用.fscanf 需要一个指向数据的指针,以便它知道可以更改变量值,而 printf 则不需要.

You don't use the "address of"-operator & with printf. fscanf requires a pointer to the data so it knows can change the variables value, while printf does not.

变化:

printf("iteration# %d | coord1 = %f coord2 = %f \n", i, &coordinates[i-1], &coordinates[i]);

致:

printf("iteration# %d | coord1 = %f coord2 = %f \n", i, coordinates[i-1], coordinates[i]);

这篇关于fscanf 没有正确读取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆