### Square root Function

I having trouble with the rational class
here is my assignment:

Add a square root function to the rational class. Have your program print the square root of any rational number.
I want to find the square root for numerator and denominator separatetly. divide the answer to get decimals and convert the decimal to fractions.
i got till geting the decimal but i want to convert it back to a simplified fraction

 ``123456789101112131415161718192021222324252627282930313233343536373839404142`` ``````// finding greatest common factor int gcd(int a, int b) { if (b == 0) return a; else return gcd(b, a % b); } // square root float root(float a, float b) { float num = a; float den = b; float count1 = sqrt(num); float count2 = sqrt(den); float count3 = float(count1 / count2); return count3; } // Mutator // simplifying rationals void rational::simplify() { int a1, a2, g; assert(bottom != 0); a1 = top; a2 = bottom; g = gcd(a1, a2); a1 = a1 / g; a2 = a2 / g; if (a2 < 0) { a2 = -a2; a1 = -a1; } top = a1; bottom = a2; } ``````
Last edited on
Any help would be appreciated
Not sure you can achieve that. First an observation:
 ``1234`` ``````float root(int a,int b) { return sqrt(1.0*a/b); }``````

Since you are talking about fractions, I assume that a and b are integers (not floats). Also, no reason why you should use sqrt twice.

Now back to your problem: One very simple fraction is 2/1. You know that sqrt(2.0) is not a rational number. Please explain what you want to do in this case.
Also note that sqrt and float functions introduce rounding errors. Take for example 1/9. The square root is 1/3. But, since I use float, 1/3 is about 0.3333332, or some other number, slightly different than 1/3. Even if it's 0.333333, you will write this as 333333/1000000, which does not simplify to 1/3
Topic archived. No new replies allowed.