user2785675
user2785675

Reputation: 57

Errors in a sqrt function program in c++

**Essentially I was given pseudo code:

"x = 1

repeat 10 times: x = (x + n / x) / 2

return x"

And the pseudo code for the int main function (int main function to print out my n values in the cout) at the end, in order to create a sqrt function program. I get the following errors on linux2 compiler:

: In function ‘double my_sqrt_1(double)’:

:9:1: error: expected primary-expression before ‘return’

:9:1: error: expected ‘;’ before ‘return’

: In function ‘int main()’: : 15:13: error: expected unqualified-id before ‘-’ token

:~> expected primary-expression before ‘return’

Help is much appreciated!

#include <iostream> 
#include <math.h> 
using namespace std; 

double my_sqrt_1(double n) 
{ 
for (int x= 1; x<10; ++x) 
cout<< x << '\t' << x=(x+n/x)/2 << 
return x; 
} 

int main() 
{ 
int n= 3.141459; 
int k= -100,-10,-1,0,1,10,and 100; 
for(auto k : { -100,-10,-1,0,1,10,100}){ 
n=3.14159 * pow (10.0,k); 
cout << "print n,sqrt(n),and my_sqrt_1(n)" ; 
return 0; 
} 
}

Upvotes: 0

Views: 1001

Answers (1)

Matt Lacey
Matt Lacey

Reputation: 8255

You missed a semicolon at the end of the cout line:

double my_sqrt_1(double n) 
{ 
  for (int x= 1; x<10; ++x) 
    cout<< x << '\t' << x=(x+n/x)/2;
  return x; 
} 

The clue is in the error:

:9:1: error: expected ‘;’ before ‘return’

Finding the source of compiler errors can be tricky for those new to C/C++, if you miss a semi-colon the line reported will often differ from the one containing the actual error. As in this case where the return line became part of the same statement as the line above.

Also here:

int k= -100,-10,-1,0,1,10,and 100;  

That is not how you define an array, you should read up on the basics of those since you're new to the game, which is evident here:

cout << "print n,sqrt(n),and my_sqrt_1(n)" ; 

Where you're not calling any functions but instead outputting a static string of text. You need to make the function calls and variable outputs outside of the literal string:

cout << "print " << n << "," << sqrt(n) << ", and" << my_sqrt_1(n); 

Upvotes: 3

Related Questions