1. 用C语言实现复数抽象数据类型(熟悉与复习typedef与结构体,例1.11) 2. 定义两个变量,分别使用传值与传地址的方式实现变量值的交换,并比较传递的结果(复习参数传递,程序示例1.3) 3. 同时求解最大值与最小
时间: 2024-09-17 17:03:23 浏览: 82
结构体数组的定义-第9、10章 结构体、联合体、枚举、位运算
1. 在C语言中,我们可以利用`typedef`关键字来创建新的类型名,并结合结构体来实现复数这种抽象数据类型。首先,我们创建一个名为`Complex`的结构体,包含实部`real`和虚部`imaginary`:
```c
#include <stdio.h>
typedef struct {
double real;
double imaginary;
} Complex;
// 函数声明,用于显示复数
void print_complex(const Complex c);
// 示例1.11
int main() {
Complex num1 = {3.0, 4.0}; // 创建复数 3 + 4i
Complex num2 = {5.0, -2.0}; // 创建复数 5 - 2i
printf("num1: (%f, %f)\n", num1.real, num1.imaginary);
printf("num2: (%f, %f)\n", num2.real, num2.imaginary);
return 0;
}
void print_complex(const Complex c) {
printf("(%lf, %lf)i\n", c.real, c.imaginary);
}
```
2. 要通过传值和传地址方式交换变量值,可以定义两个函数,一个接受变量地址直接操作(传址),另一个则接收复制后的变量副本进行操作(传值)。以下是示例:
```c
void swap_by_value(int a, int b) {
int temp = a;
a = b;
b = temp;
}
void swap_by_reference(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int x = 10, y = 20;
printf("Before swapping (by value): x=%d, y=%d\n", x, y);
swap_by_value(x, y); // 传值交换
printf("After swapping (by value): x=%d, y=%d\n", x, y);
x = 10; y = 20;
printf("Before swapping (by reference): x=%d, y=%d\n", x, y);
swap_by_reference(&x, &y); // 传址交换
printf("After swapping (by reference): x=%d, y=%d\n", x, y);
return 0;
}
```
3. 最大值和最小值的问题通常涉及到数组或一组数值,我们可以定义一个函数来同时获取数组的最大值和最小值:
```c
#include <stdio.h>
double find_max_min(int arr[], int n, double (*max)(const void *a, const void *b), double (*min)(const void *a, const void *b)) {
if (n <= 1) return *arr;
int first = 0;
int last = n - 1;
double max_val = max(arr + first, arr + last);
double min_val = min(arr + first, arr + last);
while (first < last) {
int mid = (first + last) / 2;
if (max_val == *arr + mid) {
first = mid + 1;
max_val = max(arr + first, arr + last);
} else {
last = mid;
}
if (min_val == *arr + mid) {
first = mid + 1;
min_val = min(arr + first, arr + last);
} else {
last = mid - 1;
}
}
return max_val, min_val;
}
double compare_numbers(const void *a, const void *b) {
return *(double*)a - *(double*)b;
}
int main() {
double array[] = {3, 7, 1, 9, 4};
int n = sizeof(array) / sizeof(array[0]);
double max, min;
max = min = find_max_min(array, n, compare_numbers, compare_numbers);
printf("Max: %f, Min: %f\n", max, min);
return 0;
}
```
阅读全文