C++ 課堂筆記(一)
說明:此筆記是學習于B站黑馬程式員的C++視頻所作的,感謝黑馬程式員的教學;如有什么不足之處,望各位賜教,僅供學習,
第一個代碼:書寫hello world
#include<iostream>
using namespace std;
int main() {
cout << "hello world" << endl;
system("pause");
return 0;
}
常量及變數
常量的定義方法有兩種;
(1)宏常量:在main檔案的上方定義,(此定義方法與C語言一樣)如:#define week 7 (定義時不用分號)
(2)const修飾變數,如:const int money = 80;
變數的定義:資料型別 變數名 = 初始值;
點擊查看代碼
#include<iostream>
using namespace std;
//1.宏常量(在main檔案上方定義)
#define Day 7
int main2() {
//變數的定義: 資料型別 變數名 = 初始值;
int a = 3;
cout << "a=" << a << endl;
//1.宏變數輸出
cout << "一周總共有 " << Day << " 天" << endl;
//2.const修飾變數
const int month=12;
cout << "一年一共有 " << month << " 個月" << endl;
system("pause");
return 0;
}
資料型別
sizeof()統計資料型別所占記憶體大小
(1)整型:
short占記憶體空間為 2 ;int占記憶體空間為 4 ;long占記憶體空間為 4 ;long long占記憶體空間為 8
//整型
short a = 4;
int b = 3;
long c = 20488;
long long d = 37529075;
cout << "short型別所占記憶體空間為:" << sizeof(short) << endl;
cout << "int型別所占記憶體空間為:" << sizeof(int) << endl;
(2)浮點型(統計小數):
float占記憶體空間為 4 ;double占記憶體空間為 8
float f1 = 3.14f;//這里加f的原因是機器默認小數是double型,
//double轉換成float是低精度轉換容易丟資料;
//加上個 'f' 就是告訴編譯器這個數是 float 型別的
double d1 = 3.1415;
cout << "f1 = " << f1 << endl;
cout << "d1 = " << d1 << endl;
cout << "float sizeof = " << sizeof(f1) << endl;
cout << "double sizeof = " << sizeof(d1) << endl;
(3)字符型:
變數只占記憶體1個位元組
char ch = 'a';
cout << "sizeof(char) : " << sizeof(char) << endl;
cout << (int)ch << endl;//輸出‘a’的ASCII碼值;
ch = 65;//'A'的ASCII碼值為65 注:大小寫的a的ASCII碼值相差32
cout << ch << endl;
(4)字串型:
1、c風格字串:char 變數名[] = "字串值";(和c語言定義字串一樣)
char str1[] = "hello world";
cout << str1 << endl;
cout << str1[2] << endl;
2、string 變數名 = "字串值";(注:需加入頭檔案 #include
#include<iostream>
using namespace std;
#include<string> //注意后面是沒有分號的
int main() {
string str = "Hello world!";
cout << str << endl;
}
(5)bool型別:
判斷真偽(1為真,0為假),占記憶體為1個位元組;
注:java中是boolean;而c++中是bool,
bool flag = true;
cout << flag << endl; // 1
flag = false;
cout << flag << endl; // 0
cout << "size of bool = " << sizeof(bool) << endl; //1
cin:用于從鍵盤獲取資料
語法: cin >> 變數;
string str2;
cout << "請輸入字串變數:" << endl;
cin >> str2;
cout << str2 << endl;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/503532.html
標籤:其他
上一篇:day02
下一篇:Python獲取時光網電影資料
