各位程式設計師們,大家好!
到目前為止,我們已經學習了啟動和執行基本程式的基本元件
1 2 3 4 5 6 7 8
|
#include <iostream>
using namespace std;
int main (void){
// Code Goes Here
return 0;
}
|
在本教程中,我們將學習基本的輸入和輸出語句,以及在編寫程式時可以使用的變數型別。 這將使我們的程式更具“使用者互動性”,而不僅僅是在螢幕上顯示文字(或提示)。
首先,請確保您擁有程式的基本起始元件
1 2 3 4 5 6 7 8
|
#include <iostream>
using namespace std;
int main (void){
// Code Goes Here (You do not need to put this, it's optional)
return 0;
}
|
在兩個花括號內,刪除註釋(它只是一個佔位符,現在對我們沒有用處),然後輸入以下內容
|
cout << "Please enter a number." << endl;
|
您可能想知道
endl
是什麼。 嗯,它只是告訴編譯器,在執行完這段文字(或語句)後,我想要一個全新的行(基本上,轉到前一行下面的下一行)。
輸入上面的程式碼後,繼續編寫
就在您剛編寫的 cout (CEE-OUT) 語句下方。
您的程式碼應該完全如下所示
1 2 3 4 5 6 7 8 9
|
#include <iostream>
using namespace std;
int main (void){
cout << "Please enter a number" << endl;
cin >> number;
return 0;
}
|
cin
,是您用來從使用者那裡收集使用者輸入的語句。 這是保持程式趣味性的好方法。
但我們的程式仍然不完整。 我們尚未告訴編譯器“number”的資料型別是什麼。 嗯,這有點複雜,最好您能記住這些術語
變數型別
1. 布林值 (bool):此關鍵字通常用於程式中等於 true 或 false 的變數。
2. 字元 (char):此關鍵字用於字元。 它只能容納一個字元,例如“A”。
3. 整數 (int):此關鍵字用於數字,如 5、455 等。 有一些規則(我將在下一個教程中解釋),但現在只需知道定義和何時使用的上下文。
這些是基本的變數型別,我強烈建議您記住它們。
繼續並在“cout”語句之前新增
int number;
新增此程式碼後,在“cin”語句下方新增
cout << "You typed in " << number << "!" << endl;
請務必像這樣編寫“cout”語句。 另外,每當您想在螢幕上顯示變數時,請輸入
cout << (您的變數名) << endl;
現在您的程式應該如下所示
1 2 3 4 5 6 7 8 9 10
|
#include <iostream>
using namespace std;
int main (void){
int number;
cout << "Please enter a number" << endl;
cin >> number;
cout << "You typed in " << number << "!" << endl;
return 0;
}
|
執行程式後,您應該得到
Please enter a number
(It'll wait for your number here...)
40
You typed in 40 (It displays your number here!)
|
請繼續關注第 3 部分! :)
願程式碼與你同在...