473,749 Members | 2,394 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Square root program doesn't produce the right value

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
2 3190
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
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
5452
by: user | last post by:
when i first load index.php with arguments ie: "index.php?page=x", the $_SERVERvalue is null. I then get the session id appended to each link. If i refresh the page, I get the $_SERVER I want, but if i click a link $_SERVER returns the value I want and the session id. Any ideas as to how I can get the $_SERVER to return the arguments on first page load?
4
8691
by: cplusplus | last post by:
Hello, I have newbie question. I'm stuck on this current assignment. Write a program that prompts the user for two integer values, passes the values to a function where they are multiplied together and the square root of the product is returned and displayed for the user. The function should return a double. Hint: If you multiply an integer by 1.0 the result will be a double. For example:
6
1238
by: Protoman | last post by:
I'm trying to write an encryption program, and it doesn't produce the right output; "GOOGLE" encrypted w/"GOOGLE" IS NOT "ee". Here's the code: namespace { const char vTable= { {'Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M'}, {'W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M','Q'},
2
3144
by: Clint Olsen | last post by:
Hello: I posted a thread on comp.programming awhile back asking about an algorithm I implemented on square root. The idea was to use the square root of a prime number as a convenient way to get a pseudorandom number generator. So, rather than calculate the square root to try to get a particular precision answer, you would calculate it to x number of bits. This particular function takes a radicand and the number of iterations as...
4
1737
by: Peter | last post by:
Hi I am using DateTime class and TimeOfDay.Hours attribute to return current time. It returns right value on two servers, but in one particular server it does not return right time. I checked that server's date/time setting and there everything is fine. Could someone tell, why on this server TimeOfDay.Hours do not return right value? I appreciate help of any kind Thanks Peter
14
2095
by: Tom.PesterDELETETHISSS | last post by:
Hi, I think this question requires an in depth understanding of how a browser cache works. I hope I can reach an expert here. I may have found a quirk in the asp.net documentation or I don't understand what the SetAllowResponseInBrowserHistory does. While researching caching I tried the code sample at the following page : http://msdn2.microsoft.com/library/97wcd0a4(en-us,vs.80).aspx
7
11616
by: Robert | last post by:
I have the function below. it returns a "simpleresult" which I've also included the definition of below. In VS2005 (after upgrading the project), I get a warning indicating that Function 'CloseVantive' doesn't return a value on all code paths. A null reference exception could occur at run time when the result is used. The code runs fine. But why do I get this message? How do i get rid of it? The only thing I found is if i add a...
32
4994
by: priyam.trivedi | last post by:
Hi! Could anyone tell me how to find the square root of a number without using the sqrt function. I did it by using Newton's Formula. How can it be done by using the Binomial Theorem/Taylor Series? Is there any other way of doing it rather than using series? Thank you, Priyam
2
2348
by: muler | last post by:
Hi all, This is an excerpt from the Book "Programming Microsoft Visual C#: The Language": A function evaluates to the return value. When a reference type is returned, a function is available as a left- or right-value of an assignment. Functions that return a value type are restricted to right-values of an assignment.
0
8996
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9566
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9388
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9254
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6800
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6078
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4608
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4879
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3319
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.