在日常生活中,我们总会遇到一些需要通过逻辑思考和计算来解决的问题。C语言作为一种基础且强大的编程语言,能够帮助我们用编程的方式处理这些问题,让我们的生活变得更加便捷和智能化。本文将详细解析100个实用的C语言编程实例,帮助你掌握C语言,并学会如何将其应用于解决生活中的各种难题。
实例1:计算器程序
主题句
一个简单的C语言计算器程序可以帮助我们快速进行数学运算。
#include <stdio.h>
int main() {
float num1, num2;
char operator;
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two operands: ");
scanf("%f %f", &num1, &num2);
switch (operator) {
case '+':
printf("%.1f + %.1f = %.1f", num1, num2, num1 + num2);
break;
case '-':
printf("%.1f - %.1f = %.1f", num1, num2, num1 - num2);
break;
case '*':
printf("%.1f * %.1f = %.1f", num1, num2, num1 * num2);
break;
case '/':
if (num2 != 0.0)
printf("%.1f / %.1f = %.1f", num1, num2, num1 / num2);
else
printf("Error! Division by zero.");
break;
default:
printf("Error! Invalid operator");
}
return 0;
}
实例2:温度转换程序
主题句
编写一个C语言程序,将摄氏温度转换为华氏温度。
#include <stdio.h>
int main() {
float celsius, fahrenheit;
printf("Enter temperature in Celsius: ");
scanf("%f", &celsius);
fahrenheit = (celsius * 9 / 5) + 32;
printf("Temperature in Fahrenheit: %.2f", fahrenheit);
return 0;
}
实例3:日期计算器
主题句
一个简单的日期计算器,可以计算给定日期后的第N天是星期几。
#include <stdio.h>
int isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
int getDayOfWeek(int day, int month, int year) {
int daysPerMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int dayOfWeek = day;
for (int i = 1; i < month; i++)
dayOfWeek += daysPerMonth[i];
dayOfWeek += (year - 1) * 365 + (isLeapYear(year) ? 1 : 0);
dayOfWeek = (dayOfWeek + 1) % 7;
return dayOfWeek;
}
int main() {
int day, month, year, dayOfWeek;
printf("Enter the date (dd mm yyyy): ");
scanf("%d %d %d", &day, &month, &year);
dayOfWeek = getDayOfWeek(day, month, year);
printf("The day of the week is: ");
switch (dayOfWeek) {
case 0: printf("Sunday\n"); break;
case 1: printf("Monday\n"); break;
case 2: printf("Tuesday\n"); break;
case 3: printf("Wednesday\n"); break;
case 4: printf("Thursday\n"); break;
case 5: printf("Friday\n"); break;
case 6: printf("Saturday\n"); break;
}
return 0;
}
实例4:待办事项列表
主题句
创建一个C语言程序,帮助用户管理待办事项列表。
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 100
typedef struct {
char task[256];
int done;
} TodoItem;
TodoItem todos[MAX_ITEMS];
int itemCount = 0;
void addTodoItem(const char* task) {
if (itemCount < MAX_ITEMS) {
strcpy(todos[itemCount].task, task);
todos[itemCount].done = 0;
itemCount++;
} else {
printf("Todo list is full!\n");
}
}
void markTodoDone(int index) {
if (index >= 0 && index < itemCount) {
todos[index].done = 1;
printf("Task marked as done.\n");
} else {
printf("Invalid task index.\n");
}
}
void printTodoList() {
printf("Todo List:\n");
for (int i = 0; i < itemCount; i++) {
if (!todos[i].done) {
printf("%d. %s\n", i + 1, todos[i].task);
}
}
}
int main() {
// 示例:添加一些待办事项
addTodoItem("Buy groceries");
addTodoItem("Read book");
addTodoItem("Walk the dog");
// 打印待办事项列表
printTodoList();
// 标记第一个待办事项为已完成
markTodoDone(0);
// 再次打印待办事项列表
printTodoList();
return 0;
}
实例5:密码验证器
主题句
编写一个C语言程序,用于验证用户输入的密码是否符合特定的要求。
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool isPasswordValid(const char* password) {
int length = strlen(password);
bool hasDigit = false, hasLetter = false;
for (int i = 0; i < length; i++) {
if (password[i] >= '0' && password[i] <= '9')
hasDigit = true;
else if ((password[i] >= 'A' && password[i] <= 'Z') || (password[i] >= 'a' && password[i] <= 'z'))
hasLetter = true;
}
return (length >= 8 && hasDigit && hasLetter);
}
int main() {
char password[256];
printf("Enter your password: ");
scanf("%s", password);
if (isPasswordValid(password)) {
printf("Password is valid!\n");
} else {
printf("Password is invalid. It must be at least 8 characters long and contain at least one digit and one letter.\n");
}
return 0;
}
实例6:倒计时器
主题句
创建一个C语言程序,实现一个简单的倒计时器。
#include <stdio.h>
#include <time.h>
void countdown(int seconds) {
time_t start, end;
double elapsed;
start = time(NULL);
end = start + seconds;
while (time(NULL) < end) {
elapsed = end - time(NULL);
printf("\r%02d:%02d:%02d", (int)elapsed / 3600, (int)(elapsed % 3600) / 60, (int)elapsed % 60);
fflush(stdout);
sleep(1);
}
printf("\n");
}
int main() {
int seconds;
printf("Enter the number of seconds for the countdown: ");
scanf("%d", &seconds);
printf("Countdown started. Time's up!\n");
countdown(seconds);
return 0;
}
实例7:图书管理系统
主题句
设计一个简单的C语言程序,用于管理图书的借阅和归还。
#include <stdio.h>
#include <string.h>
#define MAX_BOOKS 100
typedef struct {
char title[256];
char author[256];
int available;
} Book;
Book library[MAX_BOOKS];
int bookCount = 0;
void addBook(const char* title, const char* author) {
if (bookCount < MAX_BOOKS) {
strcpy(library[bookCount].title, title);
strcpy(library[bookCount].author, author);
library[bookCount].available = 1;
bookCount++;
} else {
printf("Library is full!\n");
}
}
void borrowBook(const char* title) {
for (int i = 0; i < bookCount; i++) {
if (strcmp(library[i].title, title) == 0 && library[i].available) {
library[i].available = 0;
printf("Book '%s' has been borrowed.\n", title);
return;
}
}
printf("Book not found or not available.\n");
}
void returnBook(const char* title) {
for (int i = 0; i < bookCount; i++) {
if (strcmp(library[i].title, title) == 0) {
library[i].available = 1;
printf("Book '%s' has been returned.\n", title);
return;
}
}
printf("Book not found.\n");
}
int main() {
// 示例:添加图书
addBook("The C Programming Language", "Kernighan and Ritchie");
addBook("Clean Code", "Robert C. Martin");
// 借阅和归还图书
borrowBook("The C Programming Language");
returnBook("The C Programming Language");
return 0;
}
实例8:学生成绩管理系统
主题句
设计一个C语言程序,用于管理学生的成绩。
#include <stdio.h>
#define MAX_STUDENTS 100
typedef struct {
char name[50];
float score;
} Student;
Student students[MAX_STUDENTS];
int studentCount = 0;
void addStudent(const char* name, float score) {
if (studentCount < MAX_STUDENTS) {
strcpy(students[studentCount].name, name);
students[studentCount].score = score;
studentCount++;
} else {
printf("Student list is full!\n");
}
}
void printStudents() {
printf("Students List:\n");
for (int i = 0; i < studentCount; i++) {
printf("%s: %.2f\n", students[i].name, students[i].score);
}
}
int main() {
// 示例:添加学生成绩
addStudent("Alice", 85.5);
addStudent("Bob", 92.0);
addStudent("Charlie", 78.3);
// 打印学生成绩列表
printStudents();
return 0;
}
实例9:银行账户管理系统
主题句
编写一个C语言程序,用于管理银行账户的存款和取款。
#include <stdio.h>
typedef struct {
char accountNumber[20];
float balance;
} BankAccount;
BankAccount accounts[100];
int accountCount = 0;
void createAccount(const char* accountNumber, float initialBalance) {
if (accountCount < 100) {
strcpy(accounts[accountCount].accountNumber, accountNumber);
accounts[accountCount].balance = initialBalance;
accountCount++;
} else {
printf("Cannot create more accounts. Account list is full.\n");
}
}
void deposit(const char* accountNumber, float amount) {
for (int i = 0; i < accountCount; i++) {
if (strcmp(accounts[i].accountNumber, accountNumber) == 0) {
accounts[i].balance += amount;
printf("Deposited %.2f into account %s. New balance: %.2f\n", amount, accountNumber, accounts[i].balance);
return;
}
}
printf("Account not found.\n");
}
void withdraw(const char* accountNumber, float amount) {
for (int i = 0; i < accountCount; i++) {
if (strcmp(accounts[i].accountNumber, accountNumber) == 0) {
if (accounts[i].balance >= amount) {
accounts[i].balance -= amount;
printf("Withdrawn %.2f from account %s. New balance: %.2f\n", amount, accountNumber, accounts[i].balance);
return;
} else {
printf("Insufficient funds in account %s.\n", accountNumber);
return;
}
}
}
printf("Account not found.\n");
}
int main() {
// 示例:创建账户和进行存款、取款操作
createAccount("123456789", 1000.0);
deposit("123456789", 500.0);
withdraw("123456789", 200.0);
return 0;
}
实例10:待办事项列表(使用文件)
主题句
将待办事项列表存储到文件中,以便持久化存储。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_ITEMS 100
typedef struct {
char task[256];
int done;
} TodoItem;
TodoItem todos[MAX_ITEMS];
int itemCount = 0;
const char* filePath = "todos.txt";
void loadTodos() {
FILE* file = fopen(filePath, "r");
if (file) {
while (fscanf(file, "%255s", todos[itemCount].task) == 1) {
todos[itemCount].done = 0;
itemCount++;
}
fclose(file);
}
}
void saveTodos() {
FILE* file = fopen(filePath, "w");
if (file) {
for (int i = 0; i < itemCount; i++) {
fprintf(file, "%s\n", todos[i].task);
}
fclose(file);
}
}
void addTodoItem(const char* task) {
if (itemCount < MAX_ITEMS) {
strcpy(todos[itemCount].task, task);
todos[itemCount].done = 0;
itemCount++;
saveTodos();
} else {
printf("Todo list is full!\n");
}
}
void markTodoDone(int index) {
if (index >= 0 && index < itemCount) {
todos[index].done = 1;
saveTodos();
printf("Task marked as done.\n");
} else {
printf("Invalid task index.\n");
}
}
void printTodoList() {
printf("Todo List:\n");
for (int i = 0; i < itemCount; i++) {
if (!todos[i].done) {
printf("%d. %s\n", i + 1, todos[i].task);
}
}
}
int main() {
loadTodos();
// 示例:添加待办事项
addTodoItem("Buy groceries");
addTodoItem("Read book");
addTodoItem("Walk the dog");
// 打印待办事项列表
printTodoList();
// 标记第一个待办事项为已完成
markTodoDone(0);
// 再次打印待办事项列表
printTodoList();
return 0;
}
以上10个实例涵盖了从简单的计算器到复杂的图书管理系统和银行账户管理系统等多个领域,通过这些实例的学习,你可以更好地理解C语言编程,并将其应用到解决生活中的实际问题。记住,编程是一种技能,需要不断地练习和实践。希望这些实例能够帮助你踏上编程之旅,发现编程的乐趣!
