C/C++ 来自 math.h 的 log10 函数产生不正确的值

C/C++ log10 function from math.h yields incorrect value

以下最小示例显示了该问题:

#include <math.h>
#include <iostream>

int main()
{
   double a = log10(1/200);
   double b = log10(0.005);

   std::cout << "The value of a is " << a << " and b is " << b << std::endl;
}

我用g++编译程序:

g++ -o math math.cpp
./math

程序的输出是:

The value of a is -inf and b is -2.30103

同样的事情发生在 C:

#include <math.h>
#include <stdio.h>

int main()
{
   double a = log10(1/200);
   double b = log10(0.005);

   printf("The value of a is %f and b is %f\n", a, b);
}

我用gcc编译程序:

gcc -o math math.c -lm
./math

输出又是:

The value of a is -inf and b is -2.301030

这两种情况的答案都应该是-2.30103。谁能给我解释一下这是怎么回事?

1/200 正在执行整数除法,即 0,因此您正在执行 log10(0),这会得到 -inf。尝试将其更改为 log10(1.0/200.0)(或者只有其中一个需要小数)以告诉编译器进行浮点除法。