[英]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:将 n 更改为浮点数并将其读取为浮点数:
#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++;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.