【问题标题】:Instead of printing 100 it prints 99.999992而不是打印 100 它打印 99.999992
【发布时间】:2014-06-10 09:21:21
【问题描述】:

我的程序从那个文件中读取数据:

6 150

0 1.75

30 0.8

60 0.5

70 1

120 0.1

140 0.9

并将这些数字(从第二行开始)插入到结构数组中,然后计算“时间”。结果很好,但只有一个;第三个('time')是 100,但输出是 99.999992。

这是程序:

#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 );
}

【问题讨论】:

标签: c struct output


【解决方案1】:

这是因为浮点数的精度有限。如果您想知道原因,请更深入地了解浮点数是如何存储在内存中的。 http://en.m.wikipedia.org/wiki/Floating_point.

【讨论】:

  • 它是 not 因为精度。即使你有无限的精度,你仍然不能正确地用二进制浮点数表示 0.8
  • @luu vinh phuc 如果您拥有无限精度,您可以正确表示每个实数。不幸的是,无限的精度需要无限的大小
【解决方案2】:

典型的float 将按预期处理数学,但仅限于一定范围和精度。

该精度通常约为 6 位,可能是 7 位有效数字。请参阅&lt;float.h&gt; 中的FLT_DIG99.999992 是将数字打印到 8 位有效数字的结果。使用printf("%.5e", some_float) 会将输出限制为实际精度。

使用double 而不是float 通常会提供额外的范围和精度。但同样的问题也会发生,尽管数量更多。


正如许多其他人所说,有许多问题导致总和打印为99.999992 而不是100.0

首先,总和很可能恰好是99.99999237060546875,即之前的float,假设binary32,到100.0。将像 99.99999237060546875 这样的数字打印到 8 个有效位置超出了 C 中 float 的合理精度预期。"%f" 打印小数点后有 6 位数字的数字。由于号码是99.99999237060546875,因此打印了一个带有 2 + 6 位有效数字的整数 99.999992

2nd:各种数学运算的结果不准确。 1.0/3.0 会出现这种情况,但100 + 0.1 也会出现这种情况。经典参考文献What Every Computer Scientist Should Know About Floating-Point Arithmetic 中概述了这个想法

3、召回浮点数不是线性的,而是对数分布的。 1.0 和 10.0 之间的数字与 10.0 和 100.0 之间的数字一样多。

【讨论】:

【解决方案3】:

您不能为此使用 Round 吗?

Round(*STRING*);

来源:http://msdn.microsoft.com/en-us/library/75ks3aby(v=vs.110).aspx

【讨论】:

  • 我需要精确度,而 Round 将其带走。
猜你喜欢
  • 2016-06-07
  • 1970-01-01
  • 1970-01-01
  • 2011-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多