c++ - C++ 中的 log base 2 精度错误

标签 c++ floating-point precision division

请解释下面给定代码的输出。我在这两种情况下得到不同的 c 值,即

情况 1:n 的值取自标准输入。 情况 2:n 的值直接写在代码中。 链接:http://www.ideone.com/UjYFQd

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

using namespace std;

int main()
{
    int c;
    int n;

    scanf("%d", &n);    //n = 64
    c = (log(n) / log(2));
    cout << c << endl;  //OUTPUT = 5

    n = 64;
    c = (log(n) / log(2));
    cout << c << endl;  //OUTPUT = 6

    return 0;
}

最佳答案

由于 float 的存储方式,您可能会看到这一点:

double result = log(n) / log(2); // where you input n as 64
int c = (int)result; // this will truncate result.  If result is 5.99999999999999, you will get 5

当您对值进行硬编码时,编译器会为您优化它:

double result = log(64) / log(2); // which is the same as 6 * log(2) / log(2)
int c = (int)result;

很可能完全被替换为:

int c = 6;

因为编译器会看到您正在使用一堆编译时常量将值存储在变量中(它会继续并在编译时处理该值)。

如果您想获得操作的整数结果,您应该使用 std::round 而不是仅仅转换为 int

int c = std::round(log(n) / log(2));

关于c++ - C++ 中的 log base 2 精度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794360/

相关文章:

c++ - Qt +启动后隐藏窗口

c++ - 优化对缓冲区的并发写入

c++ - 我可以将 vector 作为initial_sum和其他函数传递给std::accumulate吗?

Java:字节到 float /整数

C++ 浮点加法(从头开始): Negative results cannot be computed

java - 使用 Spring JdbcTemplate 用随机数填充 DB 精度

java - 基准 C++ 与 Java,不切实际的结果

c - 变量值变化。

c++ - 浮点运算 : why would order of addition matter?

python - 从字符串中读取一个 float