C 它不是打印100,而是打印99.99992
我的程序从该文件读取数据: 6150 0.1.75 30 0.8 60 0.5 70 1 120 0.1 140 0.9 并将这些数字(从第二行开始)插入到结构数组中,然后计算“时间”。结果很好,但只有一个;第三个(“时间”)是100,但输出是99.999992 节目如下:C 它不是打印100,而是打印99.99992,c,struct,output,C,Struct,Output,我的程序从该文件读取数据: 6150 0.1.75 30 0.8 60 0.5 70 1 120 0.1 140 0.9 并将这些数字(从第二行开始)插入到结构数组中,然后计算“时间”。结果很好,但只有一个;第三个(“时间”)是100,但输出是99.999992 节目如下: #include <stdio.h> #include <stdlib.h> int di,i,k,m; float vi,time; int n; int l; struct node {
#include <stdio.h>
#include <stdlib.h>
int di,i,k,m;
float vi,time;
int n;
int l;
struct node
{
int distance;
float velocity;
}DV[500000];
struct timeslist_node
{
struct timeslist_node *left;
int winner;
int loser;
double time;
struct timelist_node *right;
};
double calctime(int d,float v);
void print_array();
main()
{
FILE *fp;
fp=fopen("candidates.txt","r");
if (fp==NULL) exit(2);
fscanf(fp,"%d %d",&n,&l);
printf("%d,%d\n",n,l);
for(i=0;i<n;i++)
{
fscanf(fp,"%d %f",&DV[i].distance,&DV[i].velocity);
}
calctime(DV[i].distance,DV[i].velocity);
print_array();
fclose(fp);
system("pause");
}
double calctime(int d,float v)
{
for(i=0;i<n;i++)
{
if (i == 0)
{
{
if (DV[n-1].velocity==DV[i].velocity)
time=-1;
}
time=((l-DV[n-1].distance)/(DV[n-1].velocity-DV[i].velocity));
m=1;
k=n;
}
else
{
{ if (DV[i-1].velocity==DV[i].velocity)
time=-1;
}
time=((DV[i].distance-DV[i-1].distance)/(DV[i-1].velocity-DV[i].velocity));
k=i;
m=i+1;
}
printf ("t %d %d=%lf\n",m,k,time);
}
}
void print_array()
{
for(i=0;i<n;i++)
printf("D[%d],V[%d] = %d %.2f\n ",i,i,DV[i].distance,DV[i].velocity );
}
#包括
#包括
int di,i,k,m;
浮动六、时间;
int n;
int l;
结构节点
{
整数距离;
浮速;
}DV[500000];
结构时间列表\u节点
{
结构时间列表_节点*左侧;
int优胜者;
失败者;
双倍时间;
结构时间列表节点*右;
};
双计算时间(整数d,浮点v);
无效打印数组();
main()
{
文件*fp;
fp=fopen(“candidates.txt”,“r”);
如果(fp==NULL)退出(2);
fscanf(fp、%d%d、&n、&l);
printf(“%d,%d\n”,n,l);
对于(i=0;i你不能用Round来表示这个吗
Round(*STRING*);
来源:这是因为浮点数的精度有限。如果您想知道原因,请深入了解浮点在内存中的存储方式。典型的float
将按预期处理数学运算,但只能在一定的范围和精度内
该精度通常约为6位,可能是7位有效数字。请参阅<99.99992
中的FLT\u DIG
,它是将一个数字打印到8位有效数字的结果。使用printf(“%.5e”,一些浮点值)
将输出限制在实际精度范围内
使用double
而不是float
通常会提供额外的范围和精度。但同样的问题也会出现,尽管使用的是更极端的数字
正如许多其他人所说,有许多问题促成了这一事实,即金额被打印为99.99992
,而不是100.0
首先,总和最有可能精确到99.9999237060546875
,这是之前的浮点值
,假设为100.0
。将99.999237060546875
这样的数字打印到8个重要位置,超出了C中浮点值
的合理精度预期。%f
打印一个小数点后有6位数字的数字。由于该数字是99.999999 237060546875
,因此打印了一个带有2+6位有效数字的整数99.99992
第二:各种数学运算都有不精确的结果。这是1.0/3.0
所期望的,但100+0.1
也会出现这种情况。这一思想在经典参考文献中概述,每一位计算机科学家都应该了解浮点运算
第三,回想一下,浮点数不是线性的,而是对数分布的。1.0到10.0之间的数字大约和10.0到100.0之间的数字一样多。我需要精度,而舍入则需要精度。我很确定这可以归结为一个事实,float
的精度有限。这是一篇关于t浮点数。该程序应该做:(60-30)/(0.8-0.5)这是如何接近浮点数的极限的?好吧,首先,因为。阅读由德克链接的文章(是的,这是一个很长的延伸,但你将在你的余生中完全记住它)。还有一系列的数字比我链接的另一篇文章要少。这不是因为精度。即使精度不受限制,也不能用二进制浮点表示0.8correctly@luu永福如果你有无限精度,你就可以正确地表示每个实数。不幸的是,无限精度需要你帮了大忙。如果你有时间并且愿意的话,请检查我关于树木的其他问题