C 實際示例
實踐示例
此頁面包含實際專案中使用的實踐示例列表。
變數和資料型別
示例
使用變數儲存大學生的不同資料
// 學生資料
int studentID = 15;
int studentAge = 23;
float studentFee = 75.25;
char studentGrade = 'B';
// 列印變數
printf("Student id: %d\n", studentID);
printf("Student age: %d\n", studentAge);
printf("Student fee: %f\n", studentFee);
printf("Student grade: %c", studentGrade);
自己動手試一試 »
示例
計算矩形的面積(透過乘以長度和寬度)
// 建立整數變數
int length = 4;
int width = 6;
int area;
// 計算矩形的面積
area = length * width;
// 列印變數
printf("Length is: %d\n", length);
printf("Width is: %d\n", width);
printf("Area of the rectangle is: %d", area);
自己動手試一試 »
示例
使用不同的資料型別來計算和輸出物品總成本
// 建立不同資料型別的變數
int items = 50;
float cost_per_item = 9.99;
float total_cost = items * cost_per_item;
char currency = '$';
// 列印變數
printf("Number of items: %d\n", items);
printf("Cost per item: %.2f %c\n", cost_per_item, currency);
printf("Total cost = %.2f %c\n", total_cost, currency);
自己動手試一試 »
示例
計算使用者在遊戲中分數佔最高分的百分比
// 將遊戲中可能獲得的最大分數設定為 500
int maxScore = 500;
// 使用者的實際分數
int userScore = 423;
// 計算使用者分數佔最大可用分數的百分比
float percentage = (float) userScore / maxScore * 100.0;
// 列印百分比
printf("User's percentage is %.2f", percentage);
自己動手試一試 »
有關 C 語言中變數和資料型別的教程,請訪問我們的變數章節和資料型別章節。
布林值
示例
判斷一個人是否足夠大可以投票
int myAge = 25;
int votingAge = 18;
printf("%d", myAge >= votingAge); // 返回 1 (true),表示 25 歲的人可以投票!
自己動手試一試 »
您也可以將上面的程式碼包裝在 if...else
中,根據結果執行不同的操作
示例
如果 myAge
大於或等於 18
,則輸出 "Old enough to vote!"。否則輸出 "Not old enough to vote."。
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}
自己動手試一試 »
有關 C 語言中布林值的教程,請訪問我們的布林值章節。
條件(If..Else)
示例
使用 if..else 語句根據當前時間輸出一些文字
int time = 20;
if (time < 18) {
printf("Good day.");
} else {
printf("Good evening.");
}
自己動手試一試 »
示例
檢查使用者是否輸入了正確的程式碼
int doorCode = 1337;
if (doorCode == 1337) {
printf("Correct code.\nThe door is now open.");
} else {
printf("Wrong code.\nThe door remains closed.");
}
自己動手試一試 »
示例
找出數字是正數還是負數
int myNum = 10;
if (myNum > 0) {
printf("The value is a positive number.");
} else if (myNum < 0) {
printf("The value is a negative number.");
} else {
printf("The value is 0.");
}
自己動手試一試 »
示例
判斷一個人是否足夠大可以投票
int myAge = 25;
int votingAge = 18;
if (myAge >= votingAge) {
printf("Old enough to vote!");
} else {
printf("Not old enough to vote.");
}
自己動手試一試 »
示例
判斷一個數字是偶數還是奇數
int myNum = 5;
if (myNum % 2 == 0) {
printf("%d is even.\n", myNum);
} else {
printf("%d is odd.\n", myNum);
}
自己動手試一試 »
有關 C 語言中條件的教程,請訪問我們的If..Else 章節。
Switch
示例
使用星期幾的數字來計算和輸出星期幾的名稱
int day = 4;
switch (day) {
case 1
printf("Monday");
break;
case 2
printf("Tuesday");
break;
case 3
printf("Wednesday");
break;
case 4
printf("Thursday");
break;
case 5
printf("Friday");
break;
case 6
printf("Saturday");
break;
case 7
printf("Sunday");
break;
}
自己動手試一試 »
有關 C 語言中 switch 的教程,請訪問我們的Switch 章節。
While 迴圈
示例
使用 while 迴圈建立一個簡單的“倒計時”程式
int countdown = 3;
while (countdown > 0) {
printf("%d\n", countdown);
countdown--;
}
printf("Happy New Year!!\n");
自己動手試一試 »
示例
使用 while 迴圈玩“五子棋”遊戲
int dice = 1;
while (dice <= 6) {
if (dice < 6) {
printf("No Yatzy\n");
} else {
printf("Yatzy!\n");
}
dice = dice + 1;
}
自己動手試一試 »
示例
使用 while 迴圈反轉一些數字
// 一個包含一些特定數字的變數
int numbers = 12345;
// 一個儲存反轉後數字的變數
int revNumbers = 0;
// 反轉並重新排序數字
while (numbers) {
// 獲取 'numbers' 的最後一個數字並將其新增到 'revNumber'
revNumbers = revNumbers * 10 + numbers % 10;
// 從 'numbers' 中移除最後一個數字
numbers /= 10;
}
自己動手試一試 »
有關 C 語言中 while 迴圈的教程,請訪問我們的While Loop 章節。
For 迴圈
示例
使用 for 迴圈建立一個僅列印 0 和 10 之間 **偶數** 值的程式
int i;
for (i = 0; i <= 10; i = i + 2) {
printf("%d\n", i);
}
自己動手試一試 »
示例
使用 for 迴圈建立一個列印指定數字(本例中為 2)的乘法表的程式
int number = 2;
int i;
// 列印數字 2 的乘法表
for (i = 1; i <= 10; i++) {
printf("%d x %d = %d\n", number, i, number * i);
}
return 0;
自己動手試一試 »
有關 C 語言中 for 迴圈的教程,請訪問我們的For Loop 章節。
陣列
示例
建立一個計算不同年齡平均值的程式
// 一個儲存不同年齡的陣列
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
float avg, sum = 0;
int i;
// 獲取陣列的長度
int length = sizeof(ages) / sizeof(ages[0]);
// 遍歷陣列元素
for (int i = 0; i < length; i++) {
sum += ages[i];
}
// 透過將總和除以長度來計算平均值
avg = sum / length;
// 列印平均值
printf("The average age is: %.2f", avg);
自己動手試一試 »
示例
建立一個程式,查詢不同年齡中的最低年齡
// 一個儲存不同年齡的陣列
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};
// 獲取陣列的長度
int length = sizeof(ages) / sizeof(ages[0]);
// 建立一個變數並將 ages 的第一個陣列元素賦給它
int lowestAge = ages[0];
// 遍歷 ages 陣列的元素以查詢最小年齡
for (int i = 0; i < length; i++) {
if (lowestAge > ages[i]) {
lowestAge = ages[i];
}
}
自己動手試一試 »
有關 C 語言中陣列的教程,請訪問我們的Arrays 章節。
字串
示例
使用字串建立一個簡單的歡迎訊息
char message[] = "Good to see you,";
char fname[] = "John";
printf("%s %s!", message, fname);
自己動手試一試 »
示例
建立一個程式來計算特定單詞中找到的字元數
char word[] = "Computer";
printf("The word '%s' has %d characters in it.", word, strlen(word));
自己動手試一試 »
有關 C 語言中字串的教程,請訪問我們的Strings 章節。
使用者輸入
示例
獲取使用者名稱並列印
char fullName[30];
printf("Type your full name: \n");
fgets(fullName, sizeof(fullName), stdin);
printf("Hello %s", fullName);
執行示例 »
有關 C 語言中使用者輸入的教程,請訪問我們的User Input 章節。
函式
示例
使用函式建立一個將華氏度轉換為攝氏度的程式
// 將華氏度轉換為攝氏度的函式
float toCelsius(float fahrenheit) {
return (5.0 / 9.0) * (fahrenheit - 32.0);
}
int main() {
// 設定一個華氏度值
float f_value = 98.8;
// 使用華氏度值呼叫函式
float result = toCelsius(f_value);
// 列印華氏度值
printf("Fahrenheit: %.2f\n", f_value);
// 列印結果
printf("Convert Fahrenheit to Celsius: %.2f\n", result);
return 0;
}
自己動手試一試 »
有關 C 語言中函式的教程,請訪問我們的Functions 章節。
結構體
示例
使用結構體儲存和輸出汽車的不同資訊
struct Car {
char brand[50];
char model[50];
int year;
};
int main() {
struct Car car1 = {"BMW", "X5", 1999};
struct Car car2 = {"Ford", "Mustang", 1969};
struct Car car3 = {"Toyota", "Corolla", 2011};
printf("%s %s %d\n", car1.brand, car1.model, car1.year);
printf("%s %s %d\n", car2.brand, car2.model, car2.year);
printf("%s %s %d\n", car3.brand, car3.model, car3.year);
return 0;
}
自己動手試一試 »
有關 C 語言中結構體的教程,請訪問我們的Structures 章節。
記憶體管理
示例
struct list {
int *data; // 指向儲存列表項的記憶體
int numItems; // 指示列表中當前有多少項
int size; // 指示已分配記憶體中可以容納多少項
};
void addToList(struct list *myList, int item);
int main() {
struct list myList;
int amount;
// 建立一個列表,併為 10 個專案分配空間
myList.numItems = 0;
myList.size = 10;
myList.data = malloc(myList.size * sizeof(int));
// 查詢記憶體分配是否成功
if (myList.data == NULL) {
printf("Memory allocation failed");
return 1; // 以錯誤程式碼退出程式
}
// 將指定數量的專案新增到列表中
amount = 44;
for (int i = 0; i < amount; i++) {
addToList(&myList, i + 1);
}
// 顯示列表內容
for (int j = 0; j < myList.numItems; j++) {
printf("%d ", myList.data[j]);
}
// 在不再需要時釋放記憶體
free(myList.data);
myList.data = NULL;
return 0;
}
// 此函式向列表中新增一個專案
void addToList(struct list *myList, int item) {
// 如果列表已滿,則將記憶體大小調整為可容納另外 10 個專案
if (myList->numItems == myList->size) {
myList->size += 10;
myList->data = realloc( myList->data, myList->size * sizeof(int) );
}
// 將專案新增到列表末尾
myList->data[myList->numItems] = item;
myList->numItems++;
}
自己動手試一試 »
有關 C 語言中記憶體管理的教程,請訪問我們的Memory Management 章節。