C++ (二)第一個程序

第一個程序demo.cpp

編譯、運行

g++ -c demo.cpp
g++ -o demo.exe demo.o

解釋

最簡單的C++源文件

1 int main() {
2   return 0;
3}

使用cout 輸出一行字符串

  1 //this is sample for study
  2 #include <iostream>
  3
  4 int main() {
  5     std::cout << "This is a sample for study." << std::endl;
  6     return 0;
  7 } 
Screen Shot 2022-03-24 at 1.36.51 PM.png

使用命名空間

  1 //this is sample for study
  2 #include <iostream>
  3 
  4 using namespace std;
  5 int main() {
  6     cout << "This is a sample for study." << endl;
  7     return 0;
  8 }

使用變量

  1 //this is sample for study
  2 #include <iostream>
  3 
  4 using namespace std;
  5 int main() {
  7     int carrots;
  8 
  9     carrots = 25;
 10     cout << "I have " << carrots << " carrots." << endl;
 11 
 12     carrots = carrots - 1;
 13     cout << "Crunch, Crunch. Now I have "<< carrots << " carrots." << endl;
 14     return 0;
 15 }

從鍵盤輸入

  1 //this is sample for study
  2 #include <iostream>
  3 
  4 using namespace std;
  5 int main() {
  6     cout << "This is a sample for study." << endl;
  7     int carrots;
  8 
  9     carrots = 25;
 10     cout << "I have " << carrots << " carrots." << endl;
 13 
 14     cout << "Please input number:";
 15     cin >> carrots;
 16 
 17     cout << "Now ,I still hava " << carrots << " carrots." << endl;
 18 
 19     return 0;
 20 }
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容