How to get rid of an unwanted function return value?
Hello. The function square() in my program is returning a "0"
after each time it is called. I understand why it is doing it,
but I don't know how to tell it that I don't want it to do it.
For example this is what the output looks like:
x = 1, a = 3
Y is equal to 1.75
Y is equal to 1.73214
Y is equal to 1.73205
Y is equal to 1.73205
0
.... on and on, for each value of x and a that I have assigned.
What I don't want is that 0 at the bottom.
What the program does is it uses a divide and average
algorithm to find the square of a number.
I like what I have so far
but I am wondering if I used the wrong kind of loop for the problem at hand.
The reason I chose to do it this way is because
using the cout statements like I did is the way I
am most familiar with to get values to the program
without having to manually enter them.
And the only way I know how to do it that way is by using a function to assign the values to.
Essentially I have two questions:
1. Can that 0 be gotten rid of, or atleast put some
meaningful data in its place....
or 2. Am I just plain going about this the wrong way?
Code:
#include <iostream>
#include <cmath>
using namespace std;
double x; // initial approximation
double a; // number that I am looking for the square root of.
double y; // answer
double g; // x - a/x
const double errorAllow = 1.0e-5; // this is the control number to stop the while loop.
double square(double x, double a); // function to do the actual number munching.
int main()
{
cout << square(1.0, 3.0) << "\n"; // give the program some numbers to play with
cout << square(10.0, 3.0) << "\n"; // However, this style has an unwanted behavior
cout << square(0.01, 3.0) << "\n"; // of displaying a zero after each loop is
cout << square(100.0, 3.0) << "\n"; // completed.
cout << square(1.0, 4.0) << "\n";
cout << square(2.0, 4.0) << "\n";
}
double square(double x, double a)
{
cout << "x = " << x << ", a = " << a << "\n"; // lets the user know what numbers are being used.
y = (x + a/x) / 2; // init a value for x,y, and g for the while loop to work with.
x = y;
g = x - a/x;
if (g == 0)
cout << "x is a perfect square of a!\n";
while (g >= errorAllow)
{
x = y;
y = (x + a/x) / 2;
g = x - a/x;
cout << "Y is equal to " << y << "\n";
//return x,y; // NOT BEING VERY USEFUL!
}
return 0;
}
/* this code was to manually enter in values for x and a
** for debugging, I moved it here to get it out of my way */
/* cout << "Enter a value for x: " << x <<"\n";
cin >> x;
cout << "\nEnter a value for a: " << a <<;
cin >> a; */