我有多个数据文件,其中包含两列科学格式的数字,如下所示:
-6.000000E-2 0.000000E+0
1.060000E+0 0.000000E+0
2.510000E+0 0.000000E+0
2.700000E+0 5.000000E-2
2.735000E+0 5.000000E-2
2.755000E+0 1.000000E-1
2.775000E+0 1.500000E-1
2.785000E+0 1.500000E-1
2.790000E+0 2.000000E-1
2.805000E+0 2.500000E-1
2.810000E+0 3.500000E-1
2.815000E+0 4.000000E-1
2.820000E+0 5.000000E-1
2.825000E+0 5.500000E-1
2.835000E+0 6.000000E-1
2.835000E+0 7.000000E-1
2.840000E+0 8.000000E-1
2.840000E+0 9.000000E-1
2.850000E+0 9.500000E-1
2.850000E+0 1.050000E+0
2.855000E+0 1.200000E+0
2.860000E+0 1.300000E+0
2.865000E+0 1.400000E+0
2.870000E+0 1.450000E+0
2.870000E+0 1.600000E+0
2.875000E+0 1.650000E+0
2.880000E+0 1.800000E+0
2.880000E+0 1.900000E+0
2.885000E+0 2.000000E+0
2.885000E+0 2.150000E+0
2.890000E+0 2.200000E+0
2.895000E+0 2.300000E+0
...
第一列是 x 数据,第二列是 y 数据。列由一个<tab>
字符分隔。文件中的行数从 300 到 400 不等。我编写了一个程序来从文件中读取值并使用第 100 和第 200 点计算梯度。从那个梯度我需要计算 x 截距(我使用第 150 个点)。这是来源:
#include <stdio.h>
#include <stdlib.h>
float **make_array(int size);
void cleanup(float **array, FILE *filehandle);
int main(int argc, char **argv)
{
float **entry; //2D array to hold data; entry[0][i] holds the x_i while entry[1][i] holds y_i.
FILE *infile;
infile=fopen(argv[1], "r");
if(infile=NULL){
printf("Unable to open inpufile");
exit(1);
}
char c;
int i, numlines=0, ret;
//count number of lines in file
while((c=(fgetc(infile))!=EOF))
if(c=='\n')
numlines++;
printf("Number of lines: %d", numlines);
//array to store values from file
entry=make_array(numlines);
rewind(infile);
//read values into array, ensure correct number of arguments read
for(i=0; i<numlines; i++){
fscanf(infile, " %g\t%g\n", &entry[0][i], &entry[1][i]);
if(ret!=2){
printf("reading incorrect number of inputs from file.. Terminating");
cleanup(entry,infile);
exit(3);
}
}
//dump array contents to screen to check
for(i=0;i<numlines;i++)
printf("%f\t%f\n", entry[0][i], entry[1][i]);
//find gradient of the data between the 100th and 200th point
float gradient = (entry[1][200]-entry[1][100])/(entry[0][200]-entry[0][100]);
// use the 150th point (midpoint) and the gradient to calculate the x-intercept
float vt = (entry[1][150]/gradient) - entry[0][150];
printf("\n Threshold Voltage: %f\n", vt);
cleanup(entry, infile);
return 0;
}
float **make_array(int size)
{
int i;
float **entry = malloc(2*sizeof(float));
if(entry==NULL) exit(2);
entry[0] = malloc(size*sizeof(float));
if(entry[0]==NULL) exit(2);
for(i=0; i<size; i++) entry[0][i]==0.0;
entry[1] = malloc(size*sizeof(float));
if(entry[1]==NULL) exit(2);
for(i=0; i<size; i++) entry[1][i]==0.0;
return entry;
}
void cleanup(float **array, FILE *filehandle)
{ free(array[0]);
free(array[1]);
free(array);
fclose(filehandle);
}
该程序编译时没有错误或警告,但在执行时会产生分段错误(在 Ubuntu Linux 上)。我已经研究了很长一段时间,但仍然无法发现问题。任何帮助/意见将不胜感激。非常感谢。