定义一个比较的函数compare,出现问题warning C4715: “FunCompare”: 不是所有的控件路径都返回值
1 int FunCompare(const Fraction &f1,const Fraction &f2) 2 { 3 double number1,number2; 4 number1=f1.GetNum()/f1.GetDenom(); 5 number2=f2.GetNum()/f2.GetDenom(); 6 if (number1 == number2) 7 {return 0;} 8 else if (number1 >number2) 9 {return 1;} 10 else if (number1 <number2) 11 {return -1;} 12 }
然后,添加return 0后,改正上述warning出现的错误,但是结果总是只返回number1 == number2:
int FunCompare(const Fraction &f1,const Fraction &f2) { double number1,number2; number1=f1.GetNum()/f1.GetDenom(); number2=f2.GetNum()/f2.GetDenom(); if (number1 == number2) {return 0;} else if (number1 >number2) {return 1;} else if (number1 <number2) {return -1;} return 0; }
然后再改正,修改warning的错误,但是还是不能正确得到结果,较上边的改正方法,这个改正方法更加好点:
int FunCompare(const Fraction &f1,const Fraction &f2) { double number1,number2; number1=f1.GetNum()/f1.GetDenom(); number2=f2.GetNum()/f2.GetDenom(); if (number1 == number2) return 0; else if (number1 >number2) return 1; else return -1; }
最后一次改正:
int FunCompare(const Fraction &f1,const Fraction &f2) { double number1,number2; number1=1.0*f1.GetNum()/f1.GetDenom(); number2=1.0*f2.GetNum()/f2.GetDenom(); if (number1 == number2) return 0; else if (number1 >number2) return 1; else return -1; }
因为你不加1.0*的话,你的两个操作数是整数做除法,结果就是整数,如果乘以1.0的话,结果就是浮点数,你可以打印一下num1,num2看看加与不加*1.0的结果的。
int FunCompare(const Fraction &f1,const Fraction &f2) { double number1,number2; number1=1.0*f1.GetNum()/f1.GetDenom(); number2=1.0*f2.GetNum()/f2.GetDenom(); if (number1 == number2) return 0; else if (number1 >number2) return 1; else return -1; }