如何向 c 语言函数中传递结构体来添加两个复数?
为了在 C 编程语言中添加两个复数,用户必须将两个复数作为结构成员,并通过创建用户自定义函数对这两个数字执行加法运算。
算法
请参阅下文所给出的用于添加两个复数的算法。
Step 1: Declare struct complex with data members. Step 2: Declare name for structure and variables. Step 3: Enter real and imaginary part for first complex number at run time. Step 4: Enter real and imaginary part for second complex number at runtime Step 5: Compute addition of number1 and number2 by calling function. Go to step 7. Step 6: Print the result. Step 7: Compute addition
- Declare temp variable
- temp.real = num1.real + num2.real;
- temp.imag = num1.imag + num2.imag;
- return (temp);
示例
以下是通过向函数传递结构体以添加两个复数的 C 语言程序 -
#include <stdio.h>
typedef struct complex{
float real;
float imag;
} complex;
complex addition(complex num1, complex num2);
int main(){
complex num1, num2, value;
printf("entering real and imag parts of first complex no:
");
scanf("%f %f", &num1.real, &num1.imag);
printf("entering real and imag parts of second complex no:
");
scanf("%f %f", &num2.real, &num2.imag);
value= addition(num1, num2);
printf("result = %.1f + %.1fi", value.real, value.imag);
return 0;
}
complex addition(complex num1, complex num2){
complex temp;
temp.real = num1.real + num2.real;
temp.imag = num1.imag + num2.imag;
return (temp);
}输出
当以上程序执行时,它生成以下结果 -
entering real and imag parts of first complex no: entering real and imag parts of second complex no: result = 0.0 + 0.0i
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言
C++
C#
MongoDB
MySQL
Javascript
PHP