C++程式設計(第4版)讀書筆記_基礎知識

來源:互聯網
上載者:User

標籤:+=   浮點數   []   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版)讀書筆記_基礎知識

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.