一、基础语法实例
1. 数据类型转换
实例: 将一个浮点数转换为整数。
#include <stdio.h>
int main() {
float f = 3.14f;
int i = (int)f;
printf("浮点数转换为整数:%d\n", i);
return 0;
}
2. 条件语句
实例: 判断一个数是正数、负数还是零。
#include <stdio.h>
int main() {
int num;
printf("请输入一个整数:");
scanf("%d", &num);
if (num > 0) {
printf("%d 是正数。\n", num);
} else if (num < 0) {
printf("%d 是负数。\n", num);
} else {
printf("%d 是零。\n", num);
}
return 0;
}
二、进阶应用实例
1. 循环语句
实例: 输出1到100的偶数。
#include <stdio.h>
int main() {
for (int i = 1; i <= 100; i++) {
if (i % 2 == 0) {
printf("%d\n", i);
}
}
return 0;
}
2. 数组操作
实例: 对一个整数数组进行排序。
#include <stdio.h>
void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void bubbleSort(int arr[], int n) {
int i, j;
for (i = 0; i < n-1; i++) {
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(&arr[j], &arr[j+1]);
}
}
}
}
int main() {
int arr[] = {64, 34, 25, 12, 22, 11, 90};
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
printf("排序后的数组:\n");
for (int i=0; i < n; i++)
printf("%d ", arr[i]);
printf("\n");
return 0;
}
三、实际项目应用实例
1. 文件操作
实例: 读取文件内容并输出。
#include <stdio.h>
int main() {
FILE *file = fopen("example.txt", "r");
if (file == NULL) {
printf("文件打开失败。\n");
return 1;
}
char ch;
while ((ch = fgetc(file)) != EOF) {
putchar(ch);
}
fclose(file);
return 0;
}
2. 数据结构应用
实例: 使用链表存储整数序列并输出。
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void printList(struct Node *node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
struct Node* head = NULL;
push(&head, 20);
push(&head, 4);
push(&head, 15);
push(&head, 85);
printf("链表元素:\n");
printList(head);
return 0;
}
通过以上实例,相信你已经对C语言编程有了更深入的了解。多练习、多思考,你一定会成为一个优秀的C语言程序员!
