1.使用函数判断是否为素数:
#include <stdio.h>
int is_prime(int num) {
int i;
if (num < 2) {
return 0;
}
for (i = 2; i < num; i++) {
if (num % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if (is_prime(num)) {
printf("%d is a prime number\n", num);
} else {
printf("%d is not a prime number\n", num);
}
return 0;
}
2.使用指针交换两个变量的值:
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a, b;
printf("Enter two integers: ");
scanf("%d%d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}
3.使用结构体存储图书信息:
#include <stdio.h>
#include <string.h>
struct book {
char title[50];
char author[50];
int pages;
};
int main() {
struct book b1;
printf("Enter the title of the book: ");
scanf("%s", b1.title);
printf("Enter the author of the book: ");
scanf("%s", b1.author);
printf("Enter the number of pages in the book: ");
scanf("%d", &b1.pages);
printf("Title: %s\nAuthor: %s\nPages: %d\n", b1.title, b1.author,