c ++中除法和模数的意外结果
unexpected results of division and Modulus in c++
为什么 990099009900 / 10 在 C++ 中等于 -203843547?
#include <iostream>
using namespace std;
int main()
{
long int n = 990099009900;
cout << n / 10;
}
您需要为该大小的数字使用 long long
以便您的代码可移植。
您使用的系统 LONG_MAX
(即 std::numeric_limits<long>::max()
)小于 990099009900。
这种灵活性有其缺点,这也是引入 std::int64_t
等固定宽度类型的原因之一。
另一种方法是使用
auto n = 990099009900;
并让编译器解决它,尽管如果您接近类型限制并增加 n
.
可能会导致问题
如果你运行这里:
std::cout << "limit " << std::numeric_limits<long int>::max();
你可能会 2147483647
,就像它在 Visual Studio 上发生的那样。请尝试 long long
:
#include <iostream>
int main()
{
long long n = 990099009900;
std::cout << n / 10;
}
这 guaranteed 至少是 64 位,而 long int
不是(至少是 32 位)。 32 位不足以容纳 990099009900
.
为什么 990099009900 / 10 在 C++ 中等于 -203843547?
#include <iostream>
using namespace std;
int main()
{
long int n = 990099009900;
cout << n / 10;
}
您需要为该大小的数字使用 long long
以便您的代码可移植。
您使用的系统 LONG_MAX
(即 std::numeric_limits<long>::max()
)小于 990099009900。
这种灵活性有其缺点,这也是引入 std::int64_t
等固定宽度类型的原因之一。
另一种方法是使用
auto n = 990099009900;
并让编译器解决它,尽管如果您接近类型限制并增加 n
.
如果你运行这里:
std::cout << "limit " << std::numeric_limits<long int>::max();
你可能会 2147483647
,就像它在 Visual Studio 上发生的那样。请尝试 long long
:
#include <iostream>
int main()
{
long long n = 990099009900;
std::cout << n / 10;
}
这 guaranteed 至少是 64 位,而 long int
不是(至少是 32 位)。 32 位不足以容纳 990099009900
.