Simple C++ Question. Doesn't make any sense

Does not make any sense why this code isn't working.

Here are my instructions: NOTE: in mathematics, the square root of a negative number is not real; in C++ therefore, passing such a value to the square root function is an error.

Given a double variable named areaOfSquare write the necessary code to read in a value, the area of some square, into areaOfSquare and print out the length of the side of that square.

HOWEVER: if any value read in is not valid input, just print the message "INVALID".


Here is my code. What am I doing wrong? Instead of getting 1.41 etc etc whatever square root of 2 is... it is taking 2 * 2 = 4 and square rooting that back to 2 for some reason! Why am I not getting the decimal? My double is declared and math library IS included. Any help would be great!

The OUTPUT I'm getting: User puts in 10 they get 10 back.
The OUTPUT I should be getting: User puts in 10 and they get 3.16228 back!

It's almost as if it isn't executing the sqroot statement, or it is but in a horribly wrong way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
1 #include <iostream>
2 #include <cstring>
3 #include <cmath>
4 
5 #include <iomanip>
6 
7 using namespace std;
8 
9 int main () {
10 	double areaOfSquare;
11 	
12 cin >> areaOfSquare;
13 	
14 	if(areaOfSquare >= 0)
15 	  {
16 	  sqrt(areaOfSquare);
17 	  cout << areaOfSquare << endl;
18 	  }
19 	else
20 	  {
21 	  cout << "INVALID" << endl;  
22 	  }
23 
24 	
25 }
Hi sweezy,

The sqrt function returns a double value, you need to assign this to a variable then cout it. At the moment you are just couting the number that was input, the sqrt information is ignored.

Hope all goes well :-)
TheIdeasMan,

Thank you for your time. Are you saying I need to say something like;

1
2
3
4
5
6
7
8
double length;






cout << length << endl;

?
That was the problem. The directions weren't very specific that they gave me were they? lol. Thanks for your help man.
1
2
3
4
5
double length;

length = sqrt(areaOfSquare);

std::cout << length << std::endl;


sweezy wrote:
The directions weren't very specific that they gave me were they?


But it is up to you to understand how a programming language works.
Topic archived. No new replies allowed.