Square root program doesn't produce the right value

P

Protoman

Can you help me? For 4, my square root funct gives 4 instead of 2;
here's the code:

#include <iostream>
#include <cstdlib>
using namespace std;

template<class T>
T Abs(T Nbr)
{
if( Nbr >= 0 )
return Nbr;
return -Nbr;
}

template<class T>
T Sqrt(T Nbr)
{
long double Number = Nbr / 2;
const long double Tolerance = 1.0e-7;
do Number = (Number + Nbr / Number) / 2;
while( Abs(Number * Number - Nbr) > Tolerance);
return Number;
}

int main()
{
cout << "Enter a number: " << endl;
long double num;
cin >> num;
cout << "Sqrt(" << num << ")= " << Sqrt(num) << endl;
system("PAUSE");
return 0;
}

Can you help me? Thanks.
 
K

Kai-Uwe Bux

Protoman said:
Can you help me? For 4, my square root funct gives 4 instead of 2;
here's the code:

#include <iostream>
#include <cstdlib>
using namespace std;

template<class T>
T Abs(T Nbr)
{
if( Nbr >= 0 )
return Nbr;
return -Nbr;
}

template<class T>
T Sqrt(T Nbr)
{
long double Number = Nbr / 2;
const long double Tolerance = 1.0e-7;
do Number = (Number + Nbr / Number) / 2;
while( Abs(Number * Number - Nbr) > Tolerance);
return Number;
}

int main()
{
cout << "Enter a number: " << endl;
long double num;
cin >> num;
cout << "Sqrt(" << num << ")= " << Sqrt(num) << endl;
system("PAUSE");
return 0;
}

Can you help me? Thanks.

Hm, on my machine, the program computes "Sqrt(4)= 2" just fine. The real
problem is "Sqrt(0)= nan".

Here is a fix for that:

template<class T>
T Sqrt(T Nbr)
{
long double Number = Nbr / 2;
const long double Tolerance = 1.0e-7;
while( Abs(Number * Number - Nbr) > Tolerance) {
Number = (Number + Nbr / Number) / 2;
}
return Number;
}



Best

Kai-Uwe Bux
 
K

Karl Heinz Buchegger

Protoman said:
Can you help me? For 4, my square root funct gives 4 instead of 2;
here's the code:

What's wrong with fireing up your debugger and stepping through the code
to see why it does that?

Figuring out problems in code and why it doesn't do what it should do
is *vital* in becomming a programmer. So start early, develop your
skills and learn how to use your tools.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top