From 2bd38e44ba6eeab1f8ba7d25024a769c6df67452 Mon Sep 17 00:00:00 2001 From: Mike Buland Date: Wed, 17 Apr 2013 20:52:57 -0600 Subject: You can now add and subtract fractional numbers. --- src/main.cpp | 1 + src/number.cpp | 53 +++++++++++++++++++++++++++++++++++------------------ 2 files changed, 36 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/main.cpp b/src/main.cpp index 1499285..061ebbb 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -284,6 +284,7 @@ void fractest() println("%1").arg( a ); b = "0.987"; println("%1 + %2 = %3").arg( a ).arg( b ).arg( a + b ); + println("%1 - %2 = %3").arg( a ).arg( b ).arg( a - b ); } int main( int , char *[] ) diff --git a/src/number.cpp b/src/number.cpp index 49e8a60..9fd3865 100644 --- a/src/number.cpp +++ b/src/number.cpp @@ -332,6 +332,13 @@ Bu::String Number::toString() const int Number::digit( int iIdx ) const { + if( iIdx < 0 ) + { + if( iIdx <= -iScale ) + return 0; + else + return aFrac[-1-iIdx]; + } if( iIdx >= aInt.getSize() ) return 0; return aInt[iIdx]; @@ -350,21 +357,26 @@ Number Number::add( const Number &rhs, bool bSub ) const if( bPositive == (bSub?!rhs.bPositive:rhs.bPositive)) { ret.bPositive = bPositive; - for( int j = 0; j < iPlaces || iCarry > 0; j++ ) + for( int j = 1-iScale; j < iPlaces || iCarry > 0; j++ ) { int iRes = iCarry + digit( j ) + rhs.digit( j ); -// Bu::println(" Place: %1 + %2 + (%3) = %4"). +// Bu::println(" [%5] Place: %1 + %2 + (%3) = %4"). // arg( digit(j) ).arg( rhs.digit( j ) ).arg( iCarry ) -// .arg( iRes ); - if( iRes == 0 ) +// .arg( iRes ).arg( j ); + if( j < 0 ) + ret.aFrac.set( -1-j, (iRes%iRadix) ); + else { - iZeros++; - continue; + if( iRes == 0 ) + { + iZeros++; + continue; + } + for(; iZeros > 0; iZeros-- ) + ret.aInt.append( 0 ); + + ret.aInt.append( (iRes%iRadix) ); } - for(; iZeros > 0; iZeros-- ) - ret.aInt.append( 0 ); - - ret.aInt.append( (iRes%iRadix) ); if( iRes < iRadix ) iCarry = 0; else @@ -378,21 +390,26 @@ Number Number::add( const Number &rhs, bool bSub ) const ret.bPositive = bPositive; int iRes; int iComp = (iRadix-1); - for( int j = 0; j < iPlaces; j++ ) + for( int j = 1-iScale; j < iPlaces; j++ ) { iRes = digit( j ) + (iComp-rhs.digit( j )) + iCarry; // Bu::println(" Place: %1 + %2 + (%3) = %4"). // arg( digit(j) ).arg( 9-rhs.digit( j ) ).arg( iCarry ) // .arg( iRes ); - if( iRes == 0 ) + if( j < 0 ) + ret.aFrac.set( -1-j, (iRes%iRadix) ); + else { - iZeros++; - continue; - } - for(; iZeros > 0; iZeros-- ) - ret.aInt.append( 0 ); + if( iRes == 0 ) + { + iZeros++; + continue; + } + for(; iZeros > 0; iZeros-- ) + ret.aInt.append( 0 ); - ret.aInt.append( (iRes%iRadix) ); + ret.aInt.append( (iRes%iRadix) ); + } if( iRes < iRadix ) iCarry = 0; else -- cgit v1.2.3