1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
|
#include <stdio.h> #include <stdlib.h> #include <math.h>
#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define MAXSIZE 100
typedef int ElemType;
typedef struct{ ElemType num; ElemType den; }Rational;
void InitRational(Rational *a); void RSum(Rational a,Rational b,Rational *c); void RSub(Rational a,Rational b,Rational *c); void RMul(Rational a,Rational b,Rational *c); int RDiv(Rational a,Rational b,Rational *c); void RPrint(Rational a); void RNorm(Rational *a);
void InitRational(Rational *a){ printf("Please input 分子: "); scanf("%d",&(a->num)); printf("Please input 分母: "); scanf("%d",&(a->den));
}
void RSum(Rational a,Rational b,Rational *c){ if(a.den!=b.den) { int x=a.den; a.den*=b.den; a.num*=b.den; b.num*=x; } c->num=a.num+b.num; c->den=a.den;
}
void RSub(Rational a,Rational b,Rational *c){ if(a.den!=b.den) { int x=a.den; a.den*=b.den; a.num*=b.den; b.num*=x; } c->num=a.num-b.num; c->den=a.den;
}
void RMul(Rational a,Rational b,Rational *c){ c->num=a.num*b.num; c->den=a.den*b.den;
}
int RDiv(Rational a,Rational b,Rational *c){ if(b.num) { Rational *d=c; int x=b.den; b.den=b.num; b.num=x; RMul(a,b,d); return TRUE; } else return FALSE;
}
void RPrint(Rational a){ Rational b=a; RNorm(&b); if(b.num<0 || b.den<0) printf("(-)%d/%d\n",abs(b.num),abs(b.den)); else printf("%d/%d\n",b.num,b.den);
}
void RNorm(Rational *a){ int min=(a->num); if(min>(a->den)) min=a->den; for(int i=1;i<=(min/2);i++) { if(((a->num)%i)==0 && ((a->den)%i)==0) { a->num/=i; a->den/=i; } }
}
int main(){ Rational m,n,s; InitRational(&m); RPrint(m); InitRational(&n); RPrint(n); RSum(m,n,&s); printf("%d/%d+%d/%d=",m.num,m.den,n.num,n.den); RPrint(s); RSub(m,n,&s); printf("%d/%d-%d/%d=",m.num,m.den,n.num,n.den); RPrint(s); RMul(m,n,&s); printf("%d/%d*%d/%d=",m.num,m.den,n.num,n.den); RPrint(s); if(!RDiv(m,n,&s)){ puts("Error!"); } else { printf("%d/%d(/)%d/%d=",m.num,m.den,n.num,n.den); RPrint(s); } system("pause"); return 0; }
|