程设课上题 Fraction [ For HW ]

来源:互联网 发布:java 可视化 编辑:程序博客网 时间:2024/05/16 08:04

Description:

In this assignment you are required to complete a class for fractions.

It stores the numerator and the denominator, with the lowest terms.

It is able to communicate with iostreams by the operator << and >>.

For more details, read the header file.     


犯了各种低级错误:

1. >> 的重载不必考虑 空格 的输入, 因为会自动跳过, 将其导向可以用>> 读入的类成员即可;

2.  + - * /,  的重载, 返回类型是 fraction(类) , 得到的结果并不是一个整形的数。。所以重载 == 等关系运算符时, 


bool fraction::operator==(const fraction &f) const {  if ((*this - f)._numerator)   //不能写成  if <span style="font-family: Arial, Helvetica, sans-serif;">( (*this - f) ) , 因为 *this-f 返回的是一个类,不能转化成布尔值</span>{    return false;  }  return true;}
3.  各种符号的重载,如加号:

fraction fraction::operator+(const fraction &f) const {  fraction tmp, temp(*this), tmpf(f);  tmpf.simp();  temp.simp();  tmp._denominator = gcd(temp._denominator, tmpf._denominator);  tmp._numerator = gcd(temp._denominator, tmpf._denominator) / temp._denominator      * temp._numerator      + gcd(temp._denominator, tmpf._denominator) / tmpf._denominator          * tmpf._numerator;  tmp.simp();  return tmp;  // 一开始把全部运算符+ - * / 的重载 的返回值都码成了返回(*this), 返回了原来的值, 结果输出时 全是同一个数, 蛋碎}

4.重载类外部运算符就不必在定义的时候加上类的命名空间了。。

5.化简问题:(求最小公约数) 这么水都不会,上学期我还真是白学了

首先忽略了正负号的问题,分子分母同为负号要改为正, 分子分母其中一个为负, 最后都要改成分子为负。

wrong version 1:

for(int i = 1; i < a && i < b;)   // 首先i应该循环到小于等于a b之间最小的一个数。而不是 循环到它们最小值的前一个数就终止if ( a%i == 0 &&  b%i == 0)i++;  // 如果i不能整除a,b, 造成死循, 因为没有++i;

</pre>wrong version 2:<pre name="code" class="cpp">int max = 1;for(int i  = 1; i <= a && i <=b; i++)if(a%i == 0 && b%i == 0 )max ++;  //一开始写成了max++ ,应该是max = i 才对
最后才发现处理数据太大,这方法完全会搞到 TLE,因为用循环很多遍。 

wrong version 3:


while (big % lil) {      big = lil;    lil = big%lil;  }   //不论循环体中的语句怎样调换顺序,都会产生副作用, 导致结果出错,结果变得极其简单。。。需要引入 temp变量。


6.  前后花了3,4个小时,各种浪费时间,回到了上学期不会打码的状态。。

7.  总结: 

 1)先思考!!!!越周全越好

   2)打码时越慢越好,每打一句检查一句,因为打得第一次还有兴趣检查,打完之后就再也不想检查了。。。这时可以避免很多诸如没加分号的低级错误

3) debug:

有时候会有各种TLE, RUN TIME ERROR, 很可能是数据溢出了。。

4)实在找不到解决方法,一定要立即上网看答案,找方法, 不能再拖延了,不要重复好几遍。。




0 0
原创粉丝点击