奇怪的数字转换C++

Mae*_*aus 2 c++ numbers long-integer

所以我有以下代码:

#include <iostream>
#include <string>
#include <array>

using namespace std;

int main()
{
    array<long, 3> test_vars = { 121, 319225, 15241383936 };
    for (long test_var : test_vars) {
        cout << test_var << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

在Visual Studio中,我得到以下输出:

  1. 121
  2. 319225
  3. -1938485248

在网站cpp.sh上执行的相同代码给出了以下输出:

  1. 121
  2. 319225
  3. 15241383936

我希望输出类似于cpp.sh中的输出.我不明白Visual Studio的输出.这可能很简单; 但是,如果有人能告诉我什么是错的,我会很感激的.它已经成为我烦恼的真正根源.

use*_*999 7

MSVC使用4Byte long.C++标准仅保证long至少与...一样大int.因此,a表示的最大数字signed long2.147.483.647.您输入的内容太大而无法容纳long,您将不得不使用至少为64位的更大数据类型.

另一个编译器使用64位宽long,这就是它在那里工作的原因.

您可以使用标头中int64_t定义的内容.这将保证signed int的64位大小.cstdint

你的程序会读到:

#include <cstdint>
#include <iostream>
#include <array>

using namespace std;

int main()
{
    array<int64_t, 3> test_vars = { 121, 319225, 15241383936 };
    for (int64_t test_var : test_vars) {
        cout << test_var << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)