引言
終端編程是打算機科學中的一項基本技能,而C言語作為一門歷史長久且功能富強的編程言語,在終端編程範疇有著廣泛的利用。本文將帶領妳從零開端,經由過程實戰案例進修C言語的入門知識,並逐步深刻到進階技能,讓妳在終端編程的道路上壹直進步。
1. C言語入門
1.1 C言語簡介
C言語由Dennis Ritchie在1972年開辟,是一種過程式編程言語。它存在高效性、移植性以及豐富的庫函數等特點,廣泛利用於體系編程、嵌入式開辟等範疇。
1.2 基本語法
1.2.1 數據範例
C言語的數據範例包含基本數據範例(如int、float、char等)、羅列範例跟構造體範例。
int a;
float b = 10.5;
char c = 'A';
1.2.2 變數申明跟初始化
在C言語中,申明變數時須要指定命據範例,並可能對其停止初始化。
int a = 1;
float b = 10.5;
char c = 'A';
1.2.3 把持語句
C言語中的把持語句包含前提語句(if、else if、else、switch)跟輪回語句(for、while、do…while)。
if (a > 0) {
printf("a is positive");
} else {
printf("a is not positive");
}
2. 終端編程實戰
2.1 列印「Hello, World!」順序
這是一個簡單的終端編程實戰,用於列印「Hello, World!」。
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
2.2 打算器順序
計劃一個簡單的打算器順序,實現加、減、乘、除四種運算。
#include <stdio.h>
int main() {
double num1, num2;
char operator;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf", &num1, &num2);
switch (operator) {
case '+':
printf("%.1lf + %.1lf = %.1lf\n", num1, num2, num1 + num2);
break;
case '-':
printf("%.1lf - %.1lf = %.1lf\n", num1, num2, num1 - num2);
break;
case '*':
printf("%.1lf * %.1lf = %.1lf\n", num1, num2, num1 * num2);
break;
case '/':
if (num2 != 0) {
printf("%.1lf / %.1lf = %.1lf\n", num1, num2, num1 / num2);
} else {
printf("Division by zero is not allowed.\n");
}
break;
default:
printf("Invalid operator.\n");
}
return 0;
}
3. C言語進階
3.1 指針
指針是C言語中一個非常重要的不雅點,它容許順序員直接操縱內存。
int a = 10;
int *ptr = &a;
printf("Value of a: %d\n", a);
printf("Address of a: %p\n", (void *)&a);
printf("Value of ptr: %p\n", (void *)ptr);
printf("Value of *ptr: %d\n", *ptr);
3.2 構造體
構造體是C言語中構造複雜數據範例的方法,可能封裝多個差別範例的數據。
struct student {
char name[50];
int age;
float score;
};
struct student s1;
strcpy(s1.name, "John Doe");
s1.age = 20;
s1.score = 92.5;
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Score: %.2f\n", s1.score);
3.3 靜態內存分配
C言語供給了靜態內存分配函數,如malloc、calloc跟realloc。
#include <stdio.h>
#include <stdlib.h>
int main() {
int *arr;
int n = 5;
arr = (int *)malloc(n * sizeof(int));
if (arr == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
for (int i = 0; i < n; i++) {
arr[i] = i;
}
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
free(arr);
return 0;
}
總結
經由過程本文的進修,妳曾經從C言語的入門知識開端,逐步控制了終端編程的實戰技能。盼望妳可能在現實項目中壹直應用這些知識,進步本人的編程才能。