control may reach end of non void func

This program is supposed to take the square root of a number without using the sqrt function. it keeps giving me a control may reach end of non void function error. I noted where at in the code it was giving me the error. Please help.





#include<iostream>
#include<cstdlib>
#include<cmath>
#include<iomanip>
using namespace std;
const double epsilon=1e-10;
double squareroot (double n) {
if(n<0) {
cout<<sqrt(n)<<endl;
}
double low, high;
if (n > 1)
{
low = 1;
high = n;
}
else
{ low = 0;
high = 1;}
double mid = low + (high - low)/2;
while (low <= high){
cout<<fixed;
cout<<setprecision(8)<<low<<"\t"<<setprecision(8)<<high<<"\t"<<setprecision(8)<<mid<<"\t"<<setprecision(8)<<mid*mid<<"\t"<<setprecision(8)<<(mid*mid-n)<<endl;
if (fabs(mid*mid-n)<epsilon){
return mid;}

else if (mid*mid < n){
low = mid;}
else {
high=mid;}
}
} This is where im getting the control error



int main ()
{
cout<<"Enter a number to find its square root -> ";
double n;
cin>>n;
double sq=squareroot(n);
cout<<fixed;
cout<<"sqrt("<<setprecision(6)<<n<<") "<<setprecision(6)<<sq<<endl;
return 0;
}
Last edited on
Please use the [code][/code] tags when posting code.

> } This is where im getting the control error
It means the compiler thinks there is a path through your code which doesn't result in reaching the return mid; statement.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<cmath>

const double epsilon = 1e-10;

double squareroot( double n )
{
    if( std::fabs(n) < epsilon ) return 0 ; // close enough to zero
    else if(n<0) return double(NAN) ; // not a number (we must return something)

    double low = n>1 ? 1 : 0 ;
    double high = n>1 ? n : 1 ;

    while( low <= high )
    {
        const double mid = low + (high-low)/2;

        if( std::fabs( mid*mid - n ) < epsilon ) return mid ;
        else if( mid*mid < n ) low = mid ;
        else high = mid ;
    }

    return low ; // if we reach here, low == high
}

http://coliru.stacked-crooked.com/a/09735f70380d0711
https://rextester.com/RLFN82594
Last edited on
Topic archived. No new replies allowed.