gpt4 book ai didi

c - 跳过输入文件行的程序

转载 作者:太空宇宙 更新时间:2023-11-04 07:06:31 25 4
gpt4 key购买 nike

我有一个程序,它应该询问你温度,然后在 Planck 函数中使用该温度。波长位于名为“inputwave.dat”的文件中看起来像

500
1000
1500
2000
.
.
.
11500
12000

(500 到 12,000 之间的间隔。每行各占一行)

我遇到的问题是它只打印每隔一行。

原来如此

"500 ....
1500 ....
2500 ....
3500 ...."

我希望它打印出每一行,在我的代码中发生这种情况的地方我似乎找不到任何会导致它跳过一行的内容。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double planck(double wave, double T);
int main()
{
double wave,T;
double result;
int ni;
char outfile[80];
FILE *out,*in;
in = fopen("inputwave.dat","r");
printf("\nEnter the temperature in Kelvin > ");
ni = scanf("%lf",&T);
printf("\nEnter the name of the output file > ");
ni = scanf("%s",outfile);
if((out = fopen(outfile,"w")) == NULL)
{
printf("\nCannot open %s for writing\n",outfile);
exit(1);
}
while(fscanf(in,"%lf",&wave) != EOF)
{
fscanf(in,"%d",&wave);
result = planck(wave,T);
fprintf(out,"%7.1f %e\n",wave,result);
}
fclose(out);
return(0);
}
double planck(double wave, double T)
{
static double p = 1.19106e+27;
double p1;
p1 = p/(pow(wave,5.0)*(exp(1.43879e+08/(wave*T)) - 1.0));
return(p1);
}

感谢您的宝贵时间。

最佳答案

首先,试试这个(即不要调用 fscanf 两次):

while(fscanf(in,"%lf",&wave) != EOF)
{
result = planck(wave,T);
fprintf(out,"%7.1f %e\n",wave,result);
}

之后让我们正确检查fscanf 的返回值。此函数返回成功填充的参数列表的项目数。所以,这个while的主体只有在这个返回值恰好为1时才应该被执行。所以,最好更改检查:

while(fscanf(in,"%lf",&wave) == 1)

关于c - 跳过输入文件行的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32564299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com