在Fortran中打印常量0.8804418
program hello
print *, 0.8804418
end program hello
在C版
时给出0.880441785
#include <stdio.h>
int main() {
printf("%.10g", 0.8804418);
}
在同一系统上打印0.8804418
(带有gfortran和gcc的Linux x86-64)。为什么输出不同?请注意,printf
中增加的精度不会改变输出。
这不是Is floating point math broken?或类似的重复。这个问题具体是关于Fortran和C表示(或格式化)的差异。
答案 0 :(得分:5)
默认情况下,Fortran的REAL
数字常量是单精度;但是,在C中,浮点文字具有 double 精度。
当您将0.8804418
翻译为单精度,然后在C中将其打印为double
时,您会0.8804417849
打印float x = 0.8804418f;
printf("%.10g\n", x);
REAL
Fortran的打印输出似乎是相同的数字。
Fortran的双精度d
数字语法使用后缀print *, 0.8804418d+0
:
0.88044180000000005
这会打印#include <vector>
// ...
// store the scores in a vector of size players, initialized to 0
std::vector<int> scores(players);
for ( int round = 1; round <= round_number; ++round )
{
cout << "\nRound: " << round << endl;
for ( int player = 0; player < players; ++player )
// the indeces ^^^ of arrays and vectors start from 0
{
// ... your stuff, like reading input_word...
scores[player] += input_word.length();
// here you print out the total score of the player so far
cout << "\nPlayer " << ( player + 1 ) << " Points: " << scores[player] << endl;
}
}
(demo)。