我正在实现 Lagrange插值法以计算“ y”的平方根。从用户处获取输入并将其写入文件“ xyz.dat” (二进制)为了使用Matlab绘制/显示图形。
值已正确计算,但显示图形时写入的文件同时没有 x 和 y 值。
#include <stdio.h>
#include <fstream>
int main(void)
{
float x[100],y[100],a,s=1,t=1,k=0;
int n,i,j,d=1;
printf("\n\n Enter the number of the terms of the table: ");
scanf("%d",&n);
printf("\n\n Enter the respective values of the variables x and y: \n");
for(i=0; i<n; i++)
{
scanf ("%f",&x[i]);
scanf("%f",&y[i]);
}
printf("\n\n The table you entered is as follows :\n\n");
for(i=0; i<n; i++)
{
printf("%0.3f\t%0.3f",x[i],y[i]);
printf("\n");
}
while(d==1)
{
printf(" \n\n\n Enter the value of the x to find the respective value of y\n\n\n");
scanf("%f",&a);
for(i=0; i<n; i++)
{
s=1;
t=1;
for(j=0; j<n; j++)
{
if(j!=i)
{
s=s*(a-x[j]);
t=t*(x[i]-x[j]);
}
}
k=k+((s/t)*y[i]);
}
printf("\n\n The respective value of the variable y is: %f",k);
FILE *fp;
fp = fopen("xyz.dat", "wb");
fwrite((char *)x, sizeof(double), 1, fp);
fclose(fp);
printf("\n\n Do you want to continue?\n\n Press 1 to continue and any other key to exit");
scanf("%d",&d);
}
}
预期输出应存储在文件“ xyz.dat”中,但是当我在Matlab中绘制图形时,它仅显示一些随机值,并且仅显示“ X”而不显示“ Y”
答案 0 :(得分:2)
您在哪里写y的值?我可以看到您将 x 的值写入文件
fwrite((char *)x, sizeof(double), 1, fp);
编辑: 正确将整数写入二进制文件的示例 fwrite() not working to write integer in binary file
答案 1 :(得分:1)
fwrite((char *)y, sizeof(double), 1, fp);
这是写y的值所必需的,对不起,Tag错了!