一. 預備知識
-
1. C++的編程方式
-
過程性語言 (結構化、自頂向下)、面向對象語言、泛型編程 (創建獨立于類型的代碼)
-
-
2. 創建源代碼文件的技巧
?? ?擴展名:.cpp
二. 第一個程序 - HelloWorld
-
main()
入口點
返回 int
-
標準庫
iostream
std: 標準庫的縮寫
-
Statement
一行,以 ; 結束
-
語法
1)對大小寫敏感,空格不影響
2)main返回0: 其他數字表示非正常結束
- 運行
-
#include <iostream> int main() {std::cout << "Hello World";return 0; }
快捷鍵:control+R
三、基本知識
1. 變量
-
1)int:整數 doule:雙精度浮點數
-
2)命名應該有意義
命名約定:
-
3)常量:防止變量改變
int main() {const double pi = 3.14;pi = 0; //運行將報錯return 0; }
2. 數學運算
int x = 10;
int y = x++; //y=10; x=11;
int x = 10;
int y = ++x; //y=11; x=11;
3. 標準庫
-
1)Standard Output Stream 標準輸出流
int x = 10; int y = 20; std::cout << "x = " << x << std::endl<< "y = " << y;
化簡:
#include <iostream> ? using namespace std; ? int main(){int x = 10;int y = 20;cout << "x = " << x << endl << "y = " << y;return 0; }
-
2)Standard Input Stream 標準輸入流
#include <iostream> ? using namespace std; ? int main(){cout << "Enter values for x and y";double x;double y;cin >> x >> y;count << x + y;return 0; }
-
3)使用 #include 引入標準庫,可以調用其中的函數
4. 備注
//單行注釋
//...
?
/**多行注釋,打出/*換行即可自動生成備注塊*/
四、數據類型
c++:靜態類型語言,使用前應先聲明
-
大小
1)整型:
2)小數型:
3)其他:
Using the sizeof() function, we can see the number of bytes taken by a data type.
-
初始化
double price = 99.99; float interestRate = 3.67F; //輸入時最后要加上F,否則默認為雙精度浮點數,會導致數據丟失 long fileSize = 9000L; //輸入時最后要加上L,強制轉化為長整數,否則默認為整數,會導致數據丟失 char letter = 'a'; bool isValid = false;
int number = 1.2; //number = 1; int number {}; //number = 0; int number {1.2} //報錯
也可以定義變量auto,將自動轉化類型。
-
進制
-
-
使用16進制表示顏色(RGB)
int number = 0b11111111; //number = 255;
int number = 0xff; //number = 255;
int number = 255; //number = 255;
unsighed int number = 255; //number = 255;
unsighed int number = -255; //number = 4292967041;
-
類型轉化
1)縮小轉化
int number = 1'000'000; short another = number; //another = 1690;
int number = 1'000'000; short another{number}; //報錯;
2)放大轉化
short another = 100; int number = another; //another = 100;
-
生成隨機數
#include <cstdlib>int number = rand(); //無論運行多少次都是同樣的結果,不是真正的隨機數
#include <cstdlib>srand(5); int number = rand(); //無論運行多少次都是同樣的結果,不是真正的隨機數
#include <cstdlib> #include <ctime>const short minValue = 0; const short maxValue = 9; long elapsedSeconds = time(nullptr); //返回當前時間,從 Jan 1 1970 開始到現在的秒數 srand(elapsedSeconds); int number = (rand() % (maxValue - minValue + 1)) + minValue; //用取余數決定上限,數字介于0-9