I'm doing a practice problem that gives me a function header, and a function and expects me to write the code.
I'm given(assume lowestTerms is given):
1 2 3 4 5 6 7 8 9 10 11 12 13
|
void lowestTerms(int int& n, int& d);
/*ratAdd**************************************
Add rational numbers, result expressed in lowest terms.
@parms ln-numerator for left operand
ld-denominator for left operand
rn-numerator for right operand
rd-denominator for right operand
on- result numerator
od-result denominator
@modifies on and od set to the numberator and denominator of the sum
@returns false if a denominator is zero, true otherwise.
********************************************** */
|
So I have a few questions, first of all, since it's returning true or false, do I make it a bool? It also is asking for a value(lowest terms) so I'm not sure.
Also, it says it modifies on and od, but how do I get on and od from my answer?(i.e. if I say (ln/ld)*(on/od) how can I get on and od alone? It returns me a whole number not the numerator/denominator. In C++ I coded it(below) to give me ln/ld+rn/rd=on/od, but how can I separate on/od? if I add ln to rn before I add the rational numbers it wouldn't be correct. Should I be using doubles or ints?
My codes below, this one is obviously wrong since I didn't use lowestTerms or od/on at all. My second code is below this one.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
// Example program
#include <iostream>
#include <string>
double ratAdd(double ln, double ld, double rn, double rd);
int main()
{
std::cout<<ratAdd(4,5,2,3);
}
double ratAdd(double ln, double ld, double rn, double rd){
int od=0;
int on=0;
double ans;
if(ld==0 || rd==0){
return 0; //is this correct for returning false?
}
else{
ans=(ln/ld)+(rn/rd); //this is the part I don't get. Should I have said od=ln+rn? I would think on/od would just be incorrect if I did it that way?
}
return ans;
}
|
Second attempt at code: This one seems more "correct" but I have no idea about the doubles, ints, bools, and if the math even makes sense. Saying (ln+rd)/(or+od) seems wrong to me.
1 2 3 4 5 6 7 8 9 10 11 12 13
|
double ratAdd(double ln, double ld, double rn, double rd){
int od=0;
int on=0;
if(ld==0 || rd==0){
return 0; //is this correct for returning false?
}
else{
int on=ld+rd;
int od=ln+ld;
}
return lowestTerms(on,od);
}
|
I'm really confused what the question is asking me for. I have no idea if I should be using bools, ints, or doubles, and what exactly to return.