簡體   English   中英

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM