【8.2】定义结构体类型COMPLEX表示复数,实数部分名为rp,虚数部分名为ip,都用整形表示。编写一套函数,实现复数运算,并用函数调用这些函数。函数包括:
(1)读一个复数(2)输出一个复数(3)计算这两个复数的和(4)计算着两个复数的积(5)计算一个复数的平方
#include<stdio.h>
struct COMPLEX{
int rp;
int ip;
};
int main(){
void read(struct COMPLEX *p1);
void print(struct COMPLEX *p1);
void sum(struct COMPLEX p1,struct COMPLEX p2,struct COMPLEX *p3);
void mul(struct COMPLEX p1,struct COMPLEX p2,struct COMPLEX *p3);
void sq(struct COMPLEX p1,struct COMPLEX *p3);
struct COMPLEX p1,p2,p3;
read(&p1);
print(&p1);
read(&p2);
print(&p2);
sum(p1,p2,&p3);
mul(p1,p2,&p3);
sq(p1,&p3);
return 0;
}
void read(struct COMPLEX *p1){
scanf("%d%d",&p1->rp,&p1->ip);
}
void print(struct COMPLEX *p1){
if(p1->ip<0){
printf("%d%di\n",p1->rp,p1->ip);
}else{
printf("%d+%di\n",p1->rp,p1->ip);
}
}
void sum(struct COMPLEX p1,struct COMPLEX p2,struct COMPLEX *p3){
p3->rp=p1.rp+p2.rp;
p3->ip=p1.ip+p2.ip;
print(p3);
}
void mul(struct COMPLEX p1,struct COMPLEX p2,struct COMPLEX *p3){
p3->rp=p1.rp*p2.rp-p1.ip*p2.ip;
p3->ip=p1.rp*p2.ip+p1.ip*p2.rp;
print(p3);
}
void sq(struct COMPLEX p1,struct COMPLEX *p3){
p3->rp=p1.rp*p1.rp+p1.ip*p1.ip;
p3->ip=2*p1.rp*p1.ip;
print(p3);
}
输入示例:1
2
3
4
输出示例:
可能可读性不强,是小编的问题,我会继续改正的!
【8.3】定义结构体类型RATIONAL表示一个有理数的分母和分子,分母命名为d和分子命名为n;
都用整型数表示。编写一套韩束,实现有理数的计算,并用主函数调用这些函数。函数包括:(1)计算和返回n和d的最大公约数;
(2)对有理数进行约分,分母和分子都还原成最小项;
(3)读入一个有理数,注意分母不为0;
(4)输出一个有理数;
(5)计算两个有理数的和;
#include<stdio.h>
struct RATIONAL{
int d;
int n;
};
int main(){
void read(struct RATIONAL *num);
int max(struct RATIONAL *num);
void min(struct RATIONAL *num);
void print(struct RATIONAL *num);
void sum(struct RATIONAL *num,struct RATIONAL *num2);
struct RATIONAL num1,num2;
printf("输入第一个数");
read(&num1);
min(&num1);
printf("第一个数为:");
print(&num1);
printf("输入第二个数");
read(&num2);
min(&num2);
printf("第二个数为:");
print(&num2);
printf("和为");
sum(&num1,&num2);
return 0;
}
void read(struct RATIONAL *num){
scanf("%d%d",&num->n,&num->d);
if(num->d==0){
printf("error");
read(num);
}
}
int max(struct RATIONAL *num){
struct RATIONAL x;
int a;
x.d=num->d;
x.n=num->n;
if(x.d<x.n){
a=x.d;
x.d=x.n;
x.n=a;
}
while(x.n!=0){
a=x.d%x.n;
x.d=x.n;
x.n=a;
}
return x.d;
}
void min(struct RATIONAL *num){
int x=max(num);
num->d=num->d/x;
num->n=num->n/x;
}
void print(struct RATIONAL *num){
printf("%d/%d\n",num->n,num->d);
}
void sum(struct RATIONAL *num1,struct RATIONAL *num2){
num1->n=num1->d*num2->n+num2->d*num1->n;
num1->d=num1->d*num2->d;
min(num1);
print(num1);
}
运行结果如下:
这是分母输入为0的情况:
两个更多考察的是数学能力,小编好久没学数学已经忘了很多了所以即使恶补了一下,希望大家多多包涵~有问题随时提出,大家一起交流讨论~
标签:p3,8.3,8.2,num,struct,void,林小茶,COMPLEX,p1 From: https://blog.csdn.net/qq_64385230/article/details/141282368