C 语言函数练习题及详解373


练习题 1:反转一个数字
int reverse_number(int num) {
int reversed = 0;
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
return reversed;
}

练习题 2:计算阶乘
double factorial(int num) {
double result = 1;
while (num > 0) {
result *= num;
num--;
}
return result;
}

练习题 3:查找字符串中的字符
char *find_char(char *str, char c) {
while (*str != '\0') {
if (*str == c) {
return str;
}
str++;
}
return NULL;
}

练习题 4:比较两个字符串
int compare_strings(char *str1, char *str2) {
while (*str1 != '\0' && *str2 != '\0') {
if (*str1 != *str2) {
return *str1 - *str2;
}
str1++;
str2++;
}
return *str1 - *str2;
}

练习题 5:删除字符串中的空格
char *remove_spaces(char *str) {
char *new_str = (char *)malloc(strlen(str));
char *ptr = str;
while (*ptr != '\0') {
if (*ptr != ' ') {
*new_str = *ptr;
new_str++;
}
ptr++;
}
*new_str = '\0';
return new_str;
}

练习题 6:计算两个数的最大公约数
int gcd(int a, int b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}

练习题 7:计算两个数的最小公倍数
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}

练习题 8:排序一个数组
void sort_array(int arr[], int size) {
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (arr[i] > arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
}

练习题 9:合并两个数组
int *merge_arrays(int arr1[], int size1, int arr2[], int size2) {
int *new_arr = (int *)malloc((size1 + size2) * sizeof(int));
int i = 0, j = 0, k = 0;
while (i < size1 && j < size2) {
if (arr1[i]

2024-11-25


上一篇:函数嵌套,C语言中的子函数

下一篇:C 语言中求余数的全面指南