一、C语言基础入门
1.1 变量和数据类型
在C语言中,变量是用来存储数据的容器。了解不同数据类型(如整型、浮点型、字符型等)及其占用的内存大小是编程的基础。
代码示例:
#include <stdio.h>
int main() {
int age = 25;
float salary = 5000.0;
char grade = 'A';
printf("Age: %d\n", age);
printf("Salary: %.2f\n", salary);
printf("Grade: %c\n", grade);
return 0;
}
1.2 控制语句
控制语句用于控制程序的执行流程。常见的控制语句有条件语句(if-else)、循环语句(for、while、do-while)等。
代码示例:
#include <stdio.h>
int main() {
int num = 10;
if (num > 5) {
printf("Num is greater than 5\n");
} else {
printf("Num is not greater than 5\n");
}
for (int i = 1; i <= 5; i++) {
printf("Iteration %d\n", i);
}
return 0;
}
二、C语言实战案例
2.1 计算器程序
编写一个简单的计算器程序,实现加、减、乘、除四种运算。
代码示例:
#include <stdio.h>
int main() {
char operator;
double firstNumber, secondNumber, result;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%lf %lf", &firstNumber, &secondNumber);
switch (operator) {
case '+':
result = firstNumber + secondNumber;
break;
case '-':
result = firstNumber - secondNumber;
break;
case '*':
result = firstNumber * secondNumber;
break;
case '/':
if (secondNumber != 0.0)
result = firstNumber / secondNumber;
else
printf("Division by zero is not allowed.\n");
break;
default:
printf("Invalid operator!\n");
return 1;
}
printf("Result: %.2lf\n", result);
return 0;
}
2.2 文件操作
编写一个程序,实现文件的读取和写入操作。
代码示例:
#include <stdio.h>
int main() {
FILE *file;
char ch;
// 打开文件
file = fopen("example.txt", "r");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// 读取文件内容
while ((ch = fgetc(file)) != EOF) {
printf("%c", ch);
}
// 关闭文件
fclose(file);
// 打开文件
file = fopen("example.txt", "w");
if (file == NULL) {
printf("Error opening file!\n");
return 1;
}
// 写入文件内容
fprintf(file, "Hello, World!\n");
// 关闭文件
fclose(file);
return 0;
}
2.3 字符串处理
编写一个程序,实现字符串的复制、连接、查找等操作。
代码示例:
#include <stdio.h>
#include <string.h>
int main() {
char source[] = "Hello, World!";
char destination[100];
// 字符串复制
strcpy(destination, source);
printf("Copied string: %s\n", destination);
// 字符串连接
strcat(destination, " Have a nice day!");
printf("Concatenated string: %s\n", destination);
// 字符串查找
char *pos = strstr(destination, "nice");
if (pos != NULL) {
printf("Found 'nice' at position: %ld\n", pos - destination);
}
return 0;
}
通过以上实战案例,相信你已经对C语言编程有了初步的了解。继续学习和实践,你会越来越熟练地掌握这门语言。祝你编程愉快!
