標籤:+= 浮點數 [] names mes style 情況 amp 變數賦值
變數賦值
常用的變數賦值都是用“=”去賦值的
1 int i = 2;
但是如果把一個浮點數賦值給i的話,就會造成精度損失,在C++中最好使用初始化列表的方式“{}”給變數賦值,這樣可以保證不會發生某些可能導致資訊丟失的類型轉換
1 #include <iostream>2 using namespace std;3 4 int main() {5 int i {2.3};6 return 0;7 }
比如這樣聲明,編譯器就會報錯
<source>: In function ‘int main()‘:5 : <source>:5:12: error: narrowing conversion of ‘2.2999999999999998e+0‘ from ‘double‘ to ‘int‘ inside { } [-Wnarrowing]int i {2.3};^Compiler exited with result code 1
auto通過一個for迴圈來學習使用auto的方法
1 #include <iostream> 2 using namespace std; 3 4 int main() { 5 int v[] = {0, 1, 2, 3, 4}; 6 7 for (auto x : v) { 8 cout << x << "\t"; 9 }10 cout << endl;11 12 for (auto i = 0; i < sizeof(v) / sizeof(int); ++i) {13 cout << v[i] << "\t"; 14 }15 cout << endl;16 17 for (auto x : {0, 1, 2, 3, 4}) {18 cout << x << "\t";19 }20 cout << endl;21 22 for (auto x : v) {23 x += 1;24 }25 for (auto x : v) {26 cout << x << "\t";27 }28 cout << endl;29 30 /* 對於不帶引用的情況,可以理解為對於v的每個元素將其從頭到尾依次放入x並列印 */31 for (auto & x : v) {32 x += 1;33 }34 for (auto x : v) {35 cout << x << "\t";36 }37 cout << endl;38 39 return 0;40 }
C++程式設計(第4版)讀書筆記_基礎知識