下面的最小示例显示了这个问题:
#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.30103C也会发生同样的情况:
#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。有人能向我解释一下发生了什么事吗?
发布于 2018-11-06 21:33:10
1/200正在执行整数除法,这是0,所以您正在执行log10(0),它为您提供-inf。尝试将其更改为log10(1.0/200.0) (或者其中只有一个应该需要小数点)来告诉编译器进行浮点除法。
https://stackoverflow.com/questions/53180325
复制相似问题