链接:http://www.nowcoder.com/pat/6/problem/4060
题目描述
本题要求编写程序,计算2个有理数的和、差、积、商。
输入描述:
输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数,负号只可能出现在分子前,分 母不为0。
输出描述:
分别在4行中按照“有理数1 运算符 有理数2 = 结果”的格式顺序输出2个有理数的和、差、积、商。注意输出的每个有理数必须是该有理数的 最简形式“k a/b”,其中k是整数部分,a/b是最简分数部分;若为负数,则须加括号;若除法分母为0,则输出“Inf”。题目保证正确的输出中 没有超过整型范围的整数。
输入例子:
5/3 0/6
输出例子:
1 2/3 + 0 = 1 2/3 1 2/3 - 0 = 1 2/3 1 2/3 * 0 = 0 1 2/3 / 0 = Inf 思路:多加几个变量保存输入的有理数,1.用来保存最简形式 2.用来保存计算形式,就是通分过的形式。代码写起来比较复杂,还有输入格式的要求也比较多。 浮点错误:出现了除以0的情况。
1 #include "iostream" 2 #include3 #include 4 #include 5 #include 6 #include 7 #include 8 #include 9 using namespace std; 10 11 typedef struct YLS{ 12 int z; 13 int fz; 14 int fm; 15 }YLS; 16 17 void change(YLS &yls) 18 { 19 if(yls.fm == 0) return; 20 if(yls.fz/yls.fm != 0) 21 { 22 yls.z += yls.fz/yls.fm; 23 yls.fz = yls.fz%yls.fm; 24 } 25 } 26 void tongFen(YLS &yls1, YLS &yls2) 27 { 28 29 int t1, t2; 30 t1 = yls1.fm; 31 t2 = yls2.fm; 32 yls1.fz *= t2; 33 yls1.fm *= t2; 34 yls2.fz *= t1; 35 yls2.fm *= t1; 36 } 37 void output1(YLS yls1) 38 { 39 int mark = 0; 40 if(yls1.z<0 || yls1.fz<0 ||yls1.fm<0) 41 { 42 mark = 1; 43 cout <<'('; 44 } 45 if(yls1.fz==0 && yls1.z==0) 46 { 47 cout <<0; 48 } 49 else 50 { 51 if(yls1.z == 0) 52 { 53 if(yls1.fm < 0) 54 { 55 yls1.fm = -yls1.fm; 56 yls1.fz = -yls1.fz; 57 } 58 cout < <<"/" < 0) yls1.z = -yls1.z; 76 yls1.fz = - yls1.fz; 77 } 78 cout < <<" " < <<"/" < 0) yls1.z = -yls1.z;127 yls1.fz = - yls1.fz;128 }129 cout < <<" " < <<"/" < 0) yls2.z = -yls2.z;172 yls2.fz = - yls2.fz;173 }174 cout < <<" " < <<"/" < 0) yls3.z = -yls3.z;217 yls3.fz = -yls3.fz;218 }219 cout < <<" " < <<"/" < >yls1.fz;242 getchar();243 cin >>yls1.fm;244 yls2.z = 0;245 cin >>yls2.fz;246 getchar();247 cin >>yls2.fm;248 249 yls3 = yls1;250 yls4 = yls2;251 int gys = 0;252 if(yls2.fz != 0)253 {254 gys = gcd(yls2.fz, yls2.fm);255 }256 if(gys != 0)257 {yls2.fz /= gys;258 yls2.fm /= gys;}259 gys = 0;260 if(yls1.fz != 0)261 {262 gys = gcd(yls1.fz, yls1.fm);263 }264 if(gys != 0)265 {yls1.fz /= gys;266 yls1.fm /= gys;}267 change(yls1);268 change(yls2);269 270 YLS ylsX,ylsY,ylsZ;271 ylsX = yls3;272 ylsY = yls4;273 tongFen(ylsX, ylsY);274 ylsZ.z = ylsX.z+ylsY.z;275 ylsZ.fz = ylsX.fz+ylsY.fz;276 ylsZ.fm = ylsX.fm;277 gys = 0;278 if(ylsZ.fz != 0)279 {280 gys = gcd(ylsZ.fz, ylsZ.fm);281 }282 if(gys != 0)283 {ylsZ.fz /= gys;284 ylsZ.fm /= gys;}285 change(ylsZ);286 output(yls1, yls2, '+', ylsZ);287 cout <