By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,905 Members | 1,293 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,905 IT Pros & Developers. It's quick & easy.

Square root program doesn't produce the right value

P: n/a
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.

Nov 10 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Protoman wrote:
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
Nov 10 '05 #2

P: n/a
Protoman wrote:

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.
--
Karl Heinz Buchegger
kb******@gascad.at
Nov 10 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.