2022 / 4 /16
改變所佔的記憶體空間
int
short int
long int
2 byte
4 byte
4 byte
-32678 ~ 32767
-2147483648 ~ 2147483647
-2147483648 ~ 2147483647
long long int
8 byte
-9223372036854775808 ~ 9223372036854775807
約
約
<limits.h>
檢查自己作業系統的整數上下限!
#include <limits.h>
#include <iostream>
int main(void)
{
std::cout << "Max of short: "<< SHRT_MAX << std::endl;
std::cout << "Min of short: "<< SHRT_MIN << std::endl;
std::cout << std::endl;
std::cout << "Max of int: "<< INT_MAX << std::endl;
std::cout << "Min of int: "<< INT_MIN << std::endl;
std::cout << std::endl;
std::cout << "Max of long: "<< LONG_MAX << std::endl;
std::cout << "Min of long: "<< LONG_MIN << std::endl;
std::cout << std::endl;
std::cout << "Max of long long: "<< LLONG_MAX << std::endl;
std::cout << "Min of long long: "<< LLONG_MIN << std::endl;
std::cout << std::endl;
return 0;
}#include <iostream>
#include <limits.h>
using namespace std;
int main(){
int x = INT_MAX; // x = 2147483647
cout << x << endl;
x += 1;
cout << x << endl; // x = ?
x += 1;
cout << x << endl; // x = ?
return 0;
}溢位 overflow
數值超過該型態所能表示的範圍
Ex
int 最大值為 2147483647
你把它設為2147483648
short int 最大值為 32767
你把它設為 32800
你應該注意輸入資料的大小
#include<iostream>
using namespace std;
int main(){
int t;
cin >> t;
cout << t*t << endl;
return 0;
}假設
INT_MAX
溢位
改變數值範圍
改變數值範圍
0
int
short int
long int
-32678 ~ 32767
-2147483648 ~ 2147483647
-2147483648 ~ 2147483647
long long int
-9223372036854775808 ~ 9223372036854775807
unsigned short int
0 ~ 65535
unsigned int
0 ~ 4294967295
unsigned long int
0 ~ 4294967295
unsigned long long int
0 ~
18446744073709551615
約
約
約
約
#include <limits.h>
#include <iostream>
int main(void)
{
std::cout << "Max of unsigned short: "<< USHRT_MAX << std::endl;
std::cout << std::endl;
std::cout << "Max of unsigned int: "<< UINT_MAX << std::endl;
std::cout << std::endl;
std::cout << "Max of unsigned long: "<< ULONG_MAX << std::endl;
std::cout << std::endl;
std::cout << "Max of unsigned long long: "<< ULLONG_MAX << std::endl;
std::cout << std::endl;
return 0;
}不可更動常數
不可更動常數
#include <iostream>
int main(){
const int a = 5;
const double PI = 3.14;
const int b; // 沒初始化
a = 10; // const不可更動,會噴錯
return 0;
}適合用在變數值不會被更動的時候
// not good
#include <iostream>
using std::cin;
int main(void){
int graph[1000][1000] = {};
int arr[1000] = {};
for(int i = 0; i < 1000; i++){
cin >> arr[i];
}
return 0;
}// good
#include <iostream>
using std::cin;
int main(void){
int const N = 1000;
int graph[N][N] = {};
int arr[N] = {};
for(int i = 0; i < N; i++){
cin >> arr[i];
}
return 0;
}修飾子可以用很多個
#include<iostream>
int main(){
const short int a = 0;
unsigned long int b = 0;
const static int c = 0;
const unsigned long long int d = 0;
}