抽象数据类型-分数四则运算
怎么解决结果为负数的数进行约分(第二个减法有问题)
main.cpp
#include <stdio.h>
#include "Fraction.h"
int main()
{
Fraction op1, op2, res;
int type=0;
printf("请输入第一个分数:");
scanf("%d/%d",&op1.z,&op1.m);
while(op1.m==0)
{
printf("分母不能为0,请重新输入第一个分数的分母:");
scanf("%d",&op1.m);
}
printf("\n");
printf("请输入第二个分数:");
scanf("%d/%d",&op2.z,&op2.m);
while(op2.m==0)
{
printf("分母不能为0,请重新输入第二个分数的分母:");
scanf("%d",&op2.m);
}
printf("\n");
while(1)
{
printf("请选择你想执行的操作(1--add, 2--sub, 3--mul, 4--except, 5--point, 6--exit):\n");
scanf("%d",&type);
if(type==6)
break;
else
{
switch(type)
{
case 1:
res=add(op1,op2);
point(res);
prt(res);
break;
case 2:
res=sub(op1,op2);
point(res); //这里的约分只能当结果为正数的时候成立,否则无法约分
prt(res);
break;
case 3:
res=multi(op1,op2);
point(res);
prt(res);
break;
case 4:
res=except(op1,op2);
point(res);
prt(res);
break;
case 5:
point(op1);//假设是对op1进行约分
prt(op1);
point(op2);//假设是对op2进行约分
prt(op2);
break;
}
}
}
return 0;
}
Fraction.h
#include <stdio.h>
typedef struct{
int z;//分子
int m;//分母
}Fraction;
Fraction add(Fraction x,Fraction y){
Fraction c;
if(x.m != 0 && y.m != 0)
{
c.z = x.z * y.m + y.z * x.m;
c.m = x.m * y.m;
//return c; 这条语句写在if里面的话,只有if条件满足的时候函数
//才有返回值
}
return c;
}
Fraction sub(Fraction x,Fraction y){
Fraction c;
if(x.m != 0 && y.m != 0)
{
c.z = x.z * y.m - y.z * x.m;
c.m = x.m * y.m;
}
return c;
}
Fraction multi(Fraction x,Fraction y){
Fraction c;
if(x.m != 0 && y.m != 0){
c.z = x.z * y.z;
c.m = x.m * y.m;
}
return c;
}
Fraction except(Fraction x,Fraction y){
Fraction c;
if(x.m != 0 && y.m != 0 && y.z != 0)
{
c.z = x.z * y.m;
c.m = x.m * y.z;
}
return c;
}
//函数不带参数的话,Fraction c无法从外面得到值
void point(Fraction &c){ //形参是引用,让形参的改变可以影响到实参
//Complex c;
int x = c.z;
int y = c.m;
int temp;
while(y > 0){
temp = x % y;
x = y;
y = temp;
}
c.z /= x;
c.m /= x;
}
void prt(const Fraction c){
printf("分数为:%d/%d\n",c.z, c.m);
}