C++ is calculating wrong

C++ is calculating wrong

本文关键字:wrong calculating is C++      更新时间:2023-10-16

我有一个莫名其妙的问题。这是我的代码:

int result;
result = 0 * 2 ^ 1;
std::cout << result << std::endl;

此计算的结果为 1。但是为什么?实际上它应该是 0,不是吗? 我已经尝试过使用数学库的 pow 函数,但结果也是 1:

int result;
result = std::pow(0 * 2, 1);
std::cout << result << std::endl;

在C++和许多其他计算机编程语言中,^意味着异或而不是幂。因此,它可能没有您期望的数学优先顺序。

对指数使用std::pow

const int result = std::pow(0 * 2, 1);
std::cout << result << 'n';