Reputation: 13
I am using a program with C++ that will calculate the cube root of a given float point number using Newton Methods. My program compiles, but the answer always comes out to zero. Here's the program:
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
const double epsilon = 0.00000001;
double A = 0;
double x1 = A / 10;
double x2 = 0;
int iter = 0;
cout << "Please enter a number to square. " << endl;
cin >> A;
while ((fabs(x1 - x2) > epsilon) && (iter < 100)) {
x1 = x2;
x2 = ((2 / 3 * x1) + (A / (3 * x1 * x1)));
++iter;
}
cout << "The answer is : " << x2 << endl;
}
Upvotes: 1
Views: 984
Reputation: 1193
You were assigning variables to be zero, so you weren't going into the loop and you were also dividing by zero because you set x1=x2
and along with what was said in the comments to your post. So I moved some assigning and declarations and everything worked out fine
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
const double epsilon = 0.00000001;
double A = 0;
double x1 = 0;
double x2 = 1;
int iter = 0;
cout << "Please enter a number to square. " << endl;
cin >> A;
x1 = A / 10.0;
while ((fabs(x1 - x2) > epsilon) && (iter < 100)) {
x1 = x2;
x2 = ((2.0 / 3.0 * x1) + (A / (3.0 * x1 * x1)));
++iter;
}
cout << "The answer is : " << x2 << endl;
}
Upvotes: 3