From d24badbfdaff9f0efca0a41db2ed1c7660c578cf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Marjam=C3=A4ki?= Date: Wed, 22 Aug 2012 20:50:39 +0200 Subject: [PATCH] Fixed #4068 (Endless loop inside MathLib::add()) --- lib/mathlib.cpp | 12 ++++++++---- test/testmathlib.cpp | 2 ++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/mathlib.cpp b/lib/mathlib.cpp index a00cdc3b0..799e61ae8 100644 --- a/lib/mathlib.cpp +++ b/lib/mathlib.cpp @@ -201,9 +201,11 @@ std::string MathLib::add(const std::string & first, const std::string & second) double d1 = toDoubleNumber(first); double d2 = toDoubleNumber(second); - while (d1 > 100000.0 * d2 && toString(d1+d2)==first) + + int count = 0; + while (d1 > 100000.0 * d2 && toString(d1+d2)==first && ++count<5) d2 *= 10.0; - while (d2 > 100000.0 * d1 && toString(d1+d2)==second) + while (d2 > 100000.0 * d1 && toString(d1+d2)==second && ++count<5) d1 *= 10.0; return toString(d1 + d2); @@ -217,9 +219,11 @@ std::string MathLib::subtract(const std::string &first, const std::string &secon double d1 = toDoubleNumber(first); double d2 = toDoubleNumber(second); - while (d1 > 100000.0 * d2 && toString(d1-d2)==first) + + int count = 0; + while (d1 > 100000.0 * d2 && toString(d1-d2)==first && ++count<5) d2 *= 10.0; - while (d2 > 100000.0 * d1 && toString(d1-d2)==second) + while (d2 > 100000.0 * d1 && toString(d1-d2)==second && ++count<5) d1 *= 10.0; return toString(d1 - d2); diff --git a/test/testmathlib.cpp b/test/testmathlib.cpp index b0ab04c57..62e43c94c 100644 --- a/test/testmathlib.cpp +++ b/test/testmathlib.cpp @@ -88,6 +88,7 @@ private: ASSERT_EQUALS("1" , MathLib::add("1", "0")); ASSERT_EQUALS("0" , MathLib::add("0", "0.")); ASSERT_EQUALS("1.0000001" , MathLib::add("1", "0.00000001")); // #4016 + ASSERT_EQUALS("30666.22" , MathLib::add("30666.22", "0.0")); // #4068 // subtraction ASSERT_EQUALS("254", MathLib::subtract("0xff", "1")); @@ -98,6 +99,7 @@ private: ASSERT_EQUALS("1" , MathLib::subtract("1", "0")); ASSERT_EQUALS("0" , MathLib::subtract("0", "0.")); ASSERT_EQUALS("0.99999999" , MathLib::subtract("1", "0.00000001")); // #4016 + ASSERT_EQUALS("30666.22" , MathLib::subtract("30666.22", "0.0")); // #4068 // multiply ASSERT_EQUALS("-0.003" , MathLib::multiply("-1e-3", "3"));