Hey all I'm new C++ and am having a little trouble with a simple program. The program calculates the square root of a number the user inputs. When I input -1 or any negative it comes up as 1.#ind. Ideally when the user types -1 i want -1 to come up as the answer. I know this is not right but it is whats required. Thanks.

#include <iostream>
#include <cmath>

using namespace std;

    double weirdSquareRoot(double input)
{
	return sqrt(input);
}

int main()
{
	double x, someNumber;

	cout << "Enter a number (a double): ";
	cin >> x;
	someNumber = weirdSquareRoot(x);
	cout << "The square root is " << someNumber << endl;

Recommended Answers

All 4 Replies

The square root of a negative number is an imaginary number. sqrt(-1) is not -1. To confirm this, see this calculator

The square root of a negative number is an imaginary number. sqrt(-1) is not -1. To confirm this, see this calculator

thanks for the quick reply. I really appreciate the help. So are you saying there is no way too come up with an answer if a negative is input by the user? I was shown an example and the user input -624.5 and answer resulted as -24.99. How would I go about doing this?

It makes sense that the squart root of a negative number is an imaginary number. You can not multiply two negative numbers and get a negative number. For example sqrt(-25) = -5?? But -5 * -5 != -25.You probably should have learned that in 5th grade math, or certainly high school algebra.


>>example and the user input -624.5 and answer resulted as -24.99.
Impossible. The squart root of 625.5 is indeed 24.99, but not -624.5.

No there is a way to get the square root of a negative number but as Ancient Dragon says the result is imaginary.

The square root of -1, sqrt(-1) is assigned a special value by mathematicians, i (engineers tend to use j for the same value). You can not actually write a value down for i as you can other constants like PI for instance (3.141...) i is the imaginary number that satisfies the equation

i x i = -1 (i squared equals minus one)

By having i the square root of negative numbers can be calculated because

-624.5 = -1 x 624.5

so

sqrt(-624.5) = sqrt(-1) x sqrt(624.5)

sqrt(-1) = i and we can calculate sqrt(624.5) because it is positive therefore

sqrt(-624.5) = i x sqrt(624.5) = 24.99i

If you square the result you get -624.5 showing that this is the correct square root.

commented: good answer :) +27
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.