当然,下面的代码包括了加减乘除以及分数的化简的函数,但是无法输入0,还请各位大神多多斧正
#include<stdio.h>
#include<stdlib.h>
//有理数数据类型定义
typedef struct {
int fenzi;
int fenmu;
} *ration,ration1;
//函数声明
void mul(ration num1,ration num2);//执行乘法函数并输出结果
void div(ration num1,ration num2);//执行除法函数并输出结果
void add(ration num1,ration num2);//执行加法函数并输出结果
void sep(ration num1,ration num2);//执行减法函数并输出结果
void clean(int num1,int num2);//化简分数的函数
void clean(int num1,int num2)
{
int flag = 0;
//判断两数是否发生交换
int temp;
if(num1 < num2)
{
temp = num1;
num1 = num2;
num2 = temp;
flag = 1;
}
int i = num2;//寻找最大公因数
while(i >= 1)
{
if(num1 % i == 0 && num2 % i == 0)
{
break;
}
i–;
}
num1 = num1 / i;
num2 = num2 / i;
if(flag)
{
temp = num1;
num1 = num2;
num2 = temp;
}
printf(“%d/%d\n”,num2,num1);
}
void add(ration num1,ration num2)
{
int resultmu = num1->fenmu * num2->fenmu;
int resultzi;
resultzi = num1->fenzi * num2->fenmu + num1->fenmu * num2->fenzi;
clean(resultmu,resultzi);
}
void sep(ration num1,ration num2)
{
int resultmu = num1->fenmu * num2->fenmu;
int resultzi;
resultzi = num1->fenzi * num2->fenmu – num1->fenmu * num2->fenzi;
clean(resultmu,resultzi);
}
void mul(ration num1,ration num2)
{
int resultmu = num1->fenmu * num2->fenmu;
int resultzi = num1->fenzi * num2->fenzi;
clean(resultmu,resultzi);
}
void div(ration num1,ration num2)
{
int resultmu = num1->fenmu * num2->fenzi;
int resultzi = num1->fenzi * num2->fenmu;
clean(resultmu,resultzi);
}
int main()
{
ration num1 = (ration)malloc(sizeof(ration1));
ration num2 = (ration)malloc(sizeof(ration1));
//定义两个有理数型指针以及为其分配结构体空间
if(num1 == NULL || num2 == NULL)
{
printf(“内存分配不够”);
exit(1);
}
printf(“输入第一个形如(x/y)的有理数(整数形如2/1):”);
scanf(“%d/%d”,&num1->fenzi,&num1->fenmu);
printf(“输入第二个形如(x/y)的有理数(整数形如2/1):”);
scanf(“%d/%d”,&num2->fenzi,&num2->fenmu);
//输入数据完毕
if(num1->fenmu == 0 || num2->fenmu == 0)
{
printf(“有理数分母为0,不符合数学定义,程序结束”);
exit(1);
}
printf(“对两个有理数执行乘法:”);
mul(num1 ,num2);
printf(“对两个有理数执行除法:”);
//对除法的除数不仅要判断分母的合理性,还要判断分子不能为0
if(num2->fenzi != 0)
{
div(num1 ,num2);
}
else
{
printf(“除数为0,不符合数学逻辑,故不执行除法操作”);
}
printf(“对两个有理数执行加法:”);
add(num1 ,num2);
printf(“对两个有理数执行减法:”);
sep(num1 ,num2);
free(num1);
free(num2);
//显示学号姓名
int count = 5;
while(count){
putchar(‘\n’);
count–;
}
printf(“学生姓名:罗文广\n”);
printf(“学号:%d\n”,2021102533);
return 0;
}