在C++中定義常量
阿新 • • 發佈:2019-01-26
int ble variable std con sin str efi 定義
在 C++ 中,有兩種簡單的定義常量的方式:
- 使用 #define 預處理器。
- 使用 const 關鍵字
使用 #define 預處理器:
#define identifier value;
#include <iostream> using namespace std; #define LENGTH 10 #define WIDTH 5 #define NEWLINE ‘\n‘ int main() { int area; area = LENGTH * WIDTH; cout << area; cout<< NEWLINE; return 0; }
使用 const 關鍵字:
const type variable = value;
代碼:
#include <iostream> using namespace std; int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = ‘\n‘; int area; area = LENGTH * WIDTH; cout << area; cout<< NEWLINE; return 0; }
在C++中定義常量