2

普通常見的int為32個位元

`int`希望可以表示負數和正數，
`int`可表示的範圍為: `-2^31~2^31-1`

`int`所能表示的最小數字`-2147483648`
`int`所能表示的最大數字`2147483647`

``````#include <iostream>

int main()
{
int max_interger = 2147483647;
std::cout << max_interger+1 << std::endl;
return 0;
}
``````

「最大數字」+1之後就變成「最小數字」了，

長整數型別介紹- long long

`long long`可表示的範圍為: `-2^63~2^63-1`
`#include <climits>`內有定義`LLONG_MAX`這個字，

程式範例

``````#include <iostream>
#include <climits>

int main()
{
std::cout << LLONG_MAX << std::endl;
return 0;
}
``````

用long long 測試2147483647+1吧

``````#include <iostream>

int main()
{
long long max_interger = 2147483647;
std::cout << max_interger+1 << std::endl;
return 0;
}
``````

``````#include <iostream>

int main()
{
long long max_interger = 2147483647+1;
std::cout << max_interger << std::endl;
return 0;
}
``````

``````#include <iostream>

int main()
{
long long max_interger = 2147483647;
std::cout << max_interger+1 << std::endl;
return 0;
}
``````

解法一、於數字前加上括號long long轉型

``````#include <iostream>

int main()
{
long long max_interger = (long long)2147483647+1;
std::cout << max_interger << std::endl;
return 0;
}
``````

解法二、於數字前加上後綴LL

(註: 寫小寫的英文字母「ll」或大寫的「LL」程式都可以編譯，

``````#include <iostream>

int main()
{
long long max_interger = 2147483647LL+1;
std::cout << max_interger << std::endl;
return 0;
}
``````

為什麼long long L = 10000000*10000000;會產生溢位呢?

``````#include <iostream>

int main()
{
long long L = 10000000*10000000;
std::cout << L << std::endl;
return 0;
}
``````

修正後的程式

``````#include <iostream>

int main()
{
long long L = 10000000LL*10000000;
std::cout << L << std::endl;
return 0;
}
``````

課後練習

`n`是一個大於1的`int`(保證`n`不會超過2147483647)，

``````#include <iostream>

int main()
{
int n;
std::cin >> n;
long long L = (long long)n*(n+1)/2;
std::cout << L << std::endl;
return 0;
}
``````

(注意`n`輸入`2147483647`的時候答案應為`2305843008139952128`)