【发布时间】:2015-11-23 08:36:44
【问题描述】:
我有一个任务,我们正在执行 a + b 递归操作。如果这是一个超级简单的解决方法,请多多包涵,因为我是新手。最近我犯了一些简单的错误,只是没有看到它们。
我们必须使用:
BASE CASE: if ( a == 0 ) return( b ); BASE CASE: if ( b == 0 ) return( a );
RECURSIVE CASE: else return( RecursiveAPlusB( a - 1, b - 1 ) + 2 );
-
我的标题是:
#ifndef Adder_h #define Adder_h #include <iostream> using namespace std; class Adder{ public: Adder( int a, int b ); int getA( ) const; int getB( ) const; int RecursiveAPlusB( ) const; int IterativeAPlusB( ) const; private: int myValueofA; int myValueofB; }; #endif /* Adder_h */ -
我的司机是:
#include "Adder.h" Adder::Adder(int a, int b){ myValueofA = a; myValueofB = b; } int Adder::getA( ) const{ return myValueofA;} int Adder::getB() const{ return myValueofB; } int Adder::IterativeAPlusB( ) const{ if(myValueofA==0) return myValueofB; else if(myValueofB==0) return myValueofA; else return RecursiveAPlusB(); } int Adder::RecursiveAPlusB() const{ return ((myValueofA - 1, myValueofB - 1 ) + 2) ; } -
我的主要是(作业要求的):
#include "Adder.h" #include <iostream> using namespace std; int main() { Adder ten( 6, 4 ); // All these calls should produce the // exact same answer... // namely, the number 10! cout << ten.RecursiveAPlusB( ) << endl; cout << ten.IterativeAPlusB( ) << endl; cout << ten.RecursiveAPlusB( ) << endl; Adder tenagain( 2, 8 ); cout << tenagain.RecursiveAPlusB( ) << endl; cout << tenagain.IterativeAPlusB( ) << endl; cout << tenagain.RecursiveAPlusB( ) << endl; return 0;}
请告诉我我的数学哪里出错了?!输出是 5 5 5 9 9 9,但应该都是 10。谢谢!!!
【问题讨论】:
-
Recursive是什么意思?在您的RecursiveAPlusB()中没有递归。 -
我的教授。给了我他想要的递归公式,我只是在使用它,所以我不确定......