请解释下面给出的代码的输出。两种情况下我得到不同的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;
}
最佳答案
由于浮点数的存储方式,您可能会看到此信息:
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));