![](/img/trans.png)
[英]Is it possible to get both the modulus and quotient of division in a single operation in 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;
}
如果你在這里運行:
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;
}
這保證至少是 64 位,而long int
不是(至少是 32 位)。 32 位不足以容納990099009900
。
您需要為該大小的數字使用long long
以使您的代碼可移植。
您正在使用LONG_MAX
(即std::numeric_limits<long>::max()
)小於 990099009900 的系統。
這種靈活性有其缺點,這也是引入std::int64_t
等固定寬度類型的原因之一。
另一種方法是使用
auto n = 990099009900;
並讓編譯器弄清楚,盡管如果您接近類型的限制並且增加n
,這可能會導致問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.