结构体指针输入两个复数
时间: 2024-03-05 15:23:07 浏览: 18
下面是一个示例程序,它接受两个复数的实部和虚部作为输入,并将它们存储在两个结构体指针所指向的结构体中:
```c
#include <stdio.h>
typedef struct {
double real;
double imag;
} complex;
void input_complex(complex *c)
{
printf("Enter real part: ");
scanf("%lf", &(c->real));
printf("Enter imaginary part: ");
scanf("%lf", &(c->imag));
}
int main()
{
complex c1, c2;
complex *p1 = &c1;
complex *p2 = &c2;
printf("Enter first complex number:\n");
input_complex(p1);
printf("Enter second complex number:\n");
input_complex(p2);
printf("You entered:\n");
printf("%.2f + %.2fi\n", p1->real, p1->imag);
printf("%.2f + %.2fi\n", p2->real, p2->imag);
return 0;
}
```
在此示例中,我们定义了一个复数结构体 `complex`,其中包含实部和虚部。我们还定义了一个名为 `input_complex()` 的函数,它接受一个指向 `complex` 结构体的指针,并使用 `scanf()` 函数从用户输入中读取实部和虚部值。在 `main()` 函数中,我们声明了两个 `complex` 结构体变量 `c1` 和 `c2`,并分别将它们的地址赋值给指针变量 `p1` 和 `p2`。然后,我们调用 `input_complex()` 函数两次来读取两个复数的值。最后,我们使用指针运算符 `->` 打印出每个复数的实部和虚部值。