c - 为什么相同的浮点常量在 Fortran 和 C 中打印不同?

标签 c floating-point fortran

打印常数0.8804418 Fortran 语言

   program hello
      print *, 0.8804418
   end program hello

给出0.880441785而C版本

#include <stdio.h>

int main() {
  printf("%.10g", 0.8804418);
}

打印0.8804418在同一系统上(带有 gfortran 和 gcc 的 Linux x86-64)。为什么输出不同?请注意,增加 printf 中的精度不改变输出。

这不是 Is floating point math broken? 的重复项或类似的。这个问题具体是关于 Fortran 和 C 表示(或格式)的差异。

最佳答案

默认情况下,Fortran 的 REAL数字常量是单精度;然而,在 C 中,浮点文字具有精度。

当您翻译0.8804418时转换为单精度,然后将其打印为 double在C中,你得到0.8804417849打印 ( demo )

float x = 0.8804418f;
printf("%.10g\n", x);

Fortran 的打印输出似乎是向上舍入的相同数字。

Fortran double 语法 REAL数字使用后缀 d :

print *, 0.8804418d+0

这会打印 0.88044180000000005 (demo)。

关于c - 为什么相同的浮点常量在 Fortran 和 C 中打印不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36923963/

相关文章:

c - 从终端执行时 Netbeans EXE 不工作 - CentOs

c - 在c中分配结构成员时出现段错误

javascript - JavaScript 是如何以如此精确的方式打印 0.1 的呢?

linux - 在 Fortran 中排序,未定义对 qsort_ 的引用

fortran - 什么是 : 'iunit' is used uninitialized in this function [-Wuninitialized]

fortran - Fortran 中可分配的字符变量

c - 在C中的代理服务器中转发GET请求

c - 在 C 中的函数之间传递指向结构的指针数组的问题

floating-point - 浮点不准确示例

c - float 变量初始化为 0.0 时,float 值是否保证为 0?