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