#include using namespace std; /* INSERT YOUR RAT CLASS UP HERE */ double continu
ID: 660933 • Letter: #
Question
#include
using namespace std;
/*
INSERT YOUR RAT CLASS UP HERE
*/
double continued_frac_1(int a[], int i) {
}
int* continued_frac_2(int a[], int i) {
}
Rat continued_frac_3(int a[], int i) {
}
int main() {
int array[] = {3, 7, 16, -1};
cout << "Continued fractions function 1: " <<
continued_frac_1(array, 0) << endl;
int *a = continued_frac_2(array, 0);
cout << "Continued fractions function 2: " <<
a[0] << '/' << a[1] << endl;
delete []a;
cout << "Continued fractions function 3: " <<
continued_frac_3(array, 0) << endl;;
return 0;
}
Expected Output:
Continued fractions function 1: 3.14159
Continued fractions function 2: 355/113
Continued fractions function 3: 3 16/113
-----------------------------------------------------------------------------------------------------------
1. Idea for solving problem 1:
double f(a[], i) {
if a[i+1] = -1: #base case
_____________
return a[i] + 1 / ___________ //recursive call
}
2. Pseudo-code:
int* f(a[], i) {
if (a[i+1] == -1)
return array with the right numerator and denominator
r = f(a, ______) //recursive call
new_frac = add a[i] and fraction (1 / r) //see trick
reduce and return new_frac
}
Trick: a + (1 / (b/c)) = a + (c / b) = (a*b + c) / b
3. You should use your Rat class to solve this one.
Rat f(a[], i) {
if (a[i+1] == -1)
return Rat object with the right numerator and denominator
Rat r = f(a, ______) //recursive call
return Rat object that with sum of a[i] + (1 / r) //see hint
}
Your Rat object should be "smart" enough to reduce itself to lowest terms
Hint: r is some fraction, say b/c. (1 / r) = (1 / (b/c)) = c / b
NOTE: Your actual code will not have a one-to-one correspondence
with the pseudo-code above.
Explanation / Answer
double continued_frac_1(int a[], int i) {
if a[i+1] == -1: #base case
return a[i] + 1 /continued_frac_1(a,i+1); //recursive call
}
int* continued_frac_2(int a[], int i) {
int final[2];
if (a[i+1] == -1){
return final;
}
final[0]=a[i];
r = continued_frac_2(a, i+1) //recursive call
new_frac = a[i]+(1 / r);
final[1]=new_frac;
return final;
}
Rat continued_frac_3(int a[], int i) {
if (a[i+1] == -1)
return Rat object with the right numerator and denominator
Rat r = f(a, continued_frac_3) //recursive call
return a[i]+1/r;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.