0

我正在尝试获取浮点数的长度,但它说长度是 8。我想知道有多少位数。为什么说只有8位数字?

#include <stdio.h>

int main()
{
    double n = 72382.413651;
    int len;

    len = sizeof(n);
    printf("%d\n", len);
}

我需要知道浮点数的长度,因为它有助于制作这样的对数表。

--------------------------
| 1000000 | 72382.413651 |
--------------------------
4

3 回答 3

4

的使用sizeof(n)有点误导,因为 的值n不会影响答案:你总是得到 的等价物sizeof(double),它在你的计算机上似乎是 64 位或 8 字节。回想一下,这sizeof是一个编译时操作;只有参数的类型很重要,而不是它的值。

浮点数表示中的位数通常是无意义的值,因为通常表示不精确。只有小数分隔符前的位数才能可靠确定;分隔符后面的数字通常会被截断为您喜欢的数字。

我需要知道浮点数的长度,因为我正在尝试制作这样的对数表。

与其找出你float的 s 的大小,不如将它们全部强制为特定长度。在您的调用中指定宽度和精度printf,以确保所有内容都格式化为相同的长度,并且在表格中看起来不错。

于 2013-08-31T00:51:19.363 回答
0

如果您正在寻找 中的位数double,您可能会使用sprintf并转换为字符串。然后你可以计算字符串中的字符。

这里已经讨论过了。

于 2013-08-31T00:51:40.580 回答
0

dasblinkenlight 和 Eric 的跳板——你可以做的一个例子是简单地编辑你的代码,如下所示:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    double n = 72382.413651;
    //int len;

    //len = sizeof(n);
    //printf("%d\n", len);
    printf("%5.6f\n", n);
    getchar();
}

这将打印出与声明中完全相同的值。

或者,假设您必须处理在不同位置带有小数点的数字,但希望格式在整齐的列中。你可以这样做:

#include <ansi_c.h>
#include <stdio.h>
#include <stdlib.h>

//varible format codes for varying decimal point positions    
char *format[]={"%0.9f\n",
                    "%0.8f\n",

                "%0.7f\n",
                "%0.6f\n",
                "%0.5f\n",
                "%0.4f\n",
                "%0.3f\n",
                "%0.2f\n",
                "%0.1f\n",
                "%0.0f.\n"};

int main()
{
    char val[25];
    char dp[]={"."};//will search for position of decimal point in string
    //for the purposes of illustration, create some floating point values
    double a = .723824136;
    double s = 7.23824136;
    double d = 72.3824136;
    double f = 723.824136;
    double g = 7238.24136;
    double h = 72382.4136;
    double j = 723824.136;
    double k = 7238241.36;
    double l = 72382413.6;
    double m = 723824136.;

    //put in string of standard length,   
    //format output according to decimal position
    sprintf(val, "%0.12f", a); printf( format[strcspn(val, dp)], a);
    sprintf(val, "%0.12f", s); printf( format[strcspn(val, dp)], s);
    sprintf(val, "%0.12f", d); printf( format[strcspn(val, dp)], d);
    sprintf(val, "%0.12f", f); printf( format[strcspn(val, dp)], f);
    sprintf(val, "%0.12f", g); printf( format[strcspn(val, dp)], g);
    sprintf(val, "%0.12f", h); printf( format[strcspn(val, dp)], h);
    sprintf(val, "%0.12f", j); printf( format[strcspn(val, dp)], j);
    sprintf(val, "%0.12f", k); printf( format[strcspn(val, dp)], k);
    sprintf(val, "%0.12f", l); printf( format[strcspn(val, dp)], l);
    sprintf(val, "%0.12f", m); printf( format[strcspn(val, dp)], m);
    getchar();
}
于 2013-08-31T04:54:05.477 回答