简体   繁体   中英

Problem with printf or scanf (wont print the number properly)

I am trying to read numbers from file, the function prints only the digits after the decimal point. any idea why this happens? thanks!

float Read() {    
    int i, k, w, m, n, j;    
    float number;    
    float a[m];    

    FILE *fil1;    
    fil1 = fopen("numbers.txt", "r");    
    w = 0; k = 0;     
    while (fscanf(fil1, "%d", &n) != EOF) {    
        fscanf(fil1, "%f", &number);    
        a[k] = number;    
        printf("%d => %f \n", i, a[k]);    
        w++;k++;
    }
}

change n to be float and read it as float:

#include "stdio.h"
#pragma warning(disable : 4996)

float Read()
{
    int k, w;
    float   n;
    float a[100];

    FILE* fil1;
    fil1 = fopen("numbers.txt", "r");
    w = 0; k = 0;
    while (fscanf(fil1, "%f", &n) != EOF) {
        a[k] = n;
        printf("%f \n", a[k]);
        w++; k++;
    }

    return 0;
}

You're scanning the file twice, you're basically skipping every second number. this should fix it.

float Read (){    
int i,k,w,m,n,j;    
float   number;    
float a[m];    

 FILE *fil1;    
fil1 = fopen("numbers.txt","r");    
 w=0; k = 0;     
  while (fscanf(fil1, "%f", &n) != EOF){    
a[k]=n;    
  printf ("%d => %f \n",i, a[k]);    
 w++;k++;}    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM