简体   繁体   中英

Input Loop in While function

I had a quick question about a seemingly infinite input loop in my program. I's sure it is taking place in the while loop, and am wondering if it is because my math or my coding. While loops are still new to me, so any help or explanation would be nice would be nice! This program is the start of a program using Newton's method to find the pth root of z, the residual,and improvement between loops. Also, I was wondering if a for loop might be better for my purposes. Here it is so far:

#include <iostream>
#include <cmath>

using namespace std;

double Newton(double z, int p, double &x, double &n);

int main(){
    double z, x, n, residual, bai, bri;
    int p;
    x = 1;
    n = 1;
    cin >> z >> p;
    double roots = Newton(z, p, x, n);
    cout.precision (5);
    cout << "Input: z = " << z << ", p = " << p << endl << "Root = " << x << endl;
}

double Newton(double z, int p, double &x, double &n){
    x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1))))));
    while (x != 0){
            x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1))))));
            n++;
    }
    return x;
}

In general, testing for equality with floating point arithmetic is a bad idea. I don't know if your math and/or your coding are OK, but I'd guess that the chances are x will never be exactly equal to zero. Consider changing it to something like while (fabs(x) < 1e-10) .

Nickie has a good answer as to what might be your infinite loop problem. I just wanted to add that your use of a while loop is fine in this context because you do not have a clear iteration variable.

Example:

for (int i=0; i < 10; ++i) {
    cout << i << endl;
}

Here it is clear that the variable i represents the iteration because it is the one that is being incremented at the end of each iteration as well as the one being tested as a continuation condition.

In contrast, your loop uses x to test for continuation while it is n that is incremented. This is not a clear cut case for a for loop. A for loop in your case would look like this:

double Newton(double z, int p, double &x, double &n) {
    for (x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1)))))); x != 0; n++) {
        x = (x - ((pow (x, p) - z)/(p * (pow (x, (p - 1))))));
    }
    return x;
}

This isn't terrible either but I think the while loop is clearer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM