← 從零開始學 C#
第 4 課,共 39 課 · 10 XP
變數
理論與題目說明
機器翻譯,尚未經母語人士審閱。
變數是有名字、有固定型別的記憶體格子:
int lives = 3; // 整數(32 位元)
double speed = 2.5; // 浮點數
char grade = 'A'; // 一個字元——單引號
string name = "Kai"; // 字串——雙引號
bool alive = true; // true / false
const int MaxLives = 5; // 常數:不能修改
var score = 100; // 型別由編譯器推斷(這裡是 int)——一樣是嚴格的
- C# 是強型別、靜態型別的語言:
int裡不能放字串,編譯時就會出錯; - 名字以字母或
_開頭,區域變數通常用camelCase; - 變數在使用前必須先給值——不然會出現錯誤 CS0165。
字串插值——字串前面加 $,運算式放在 { } 裡:
Console.WriteLine($"{name}: {lives} lives, speed {speed}");
題目。 建立變數 name = "Alex"、level = 7、hp = 92.5,輸出 Alex — 等級 7, HP 92.5。