C语言学习笔记
01. 基础语法事例
变量声明与赋值
#include <stdio.h>
int main() {
int age = 20; // 声明并初始化整型变量age
float height = 1.75f; // 声明并初始化浮点型变量height
printf("Age: %d, Height: %.2f\n", age, height);
return 0;
}
条件语句
#include <stdio.h>
int main() {
int score = 85;
if (score >= 60) {
printf("及格\n");
} else {
printf("不及格\n");
}
return 0;
}
循环语句
#include <stdio.h>
int main() {
for (int i = 0; i < 5; i++) {
printf("Hello, World! %dn", i);
}
return 0;
}
02. 函数使用模板
自定义函数
#include <stdio.h>
// 自定义函数,计算两个整数的和
int sum(int a, int b) {
return a + b;
}
int main() {
int result = sum(5, 3); // 调用函数
printf("The sum is: %d\n", result);
return 0;
}
03. 数组与指针事例
数组遍历
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
printf("%d ", numbers[i]);
}
printf("n");
return 0;
}
指针操作数组
#include <stdio.h>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int *ptr = numbers; // 指针指向数组首元素
for (int i = 0; i < 5; i++) {
printf("%d ", *(ptr + i)); // 通过指针访问数组元素
}
printf("\n");
return 0;
}
04. 结构体事例
定义和使用结构体
#include <stdio.h>
// 定义一个学生结构体
struct Student {
int id;
char name[50];
float score;
};
int main() {
struct Student stu = {1, "Alice", 92.5f};
printf("ID: %d, Name: %s, Score: %.2f\n", stu.id, stu.name, stu.score);
return 0;
}
05. 文件操作模板
文件写入
#include <stdio.h>
int main() {
FILE *fp = fopen("example.txt", "w"); // 打开文件用于写入
if (fp == NULL) {
perror("Error opening file");
return -1;
}
fprintf(fp, "Hello, File!n"); // 写入字符串到文件
fclose(fp); // 关闭文件
return 0