C中给定数字的近似第N个根

时间:2016-12-23 20:02:52

标签: c

我正在尝试编写一个程序,要求用户输入实数和整数。通过给定的输入,程序应该计算答案。我想在没有math.h的情况下这样做 https://en.wikipedia.org/wiki/Nth_root_algorithm是我一直遵循的算法我确定我的循环使用int iterate是我出错的地方。

#include <stdio.h>
int n, nval;
double A, oldVal, delta;
double newVal;
int i;
int iterate =1;
double root;

int main() {

while ((nval != 2 || A < 0) || n < 2){
printf("Enter real number and integer (A n):");
nval=scanf("%lf %d", &A, &n);
if (nval!=2)
    printf("Error Improperly Formatted Input\n");
else if (A<=0)
    printf("Error: Value of A must be positive\n ");
else if (n<2)
    printf("Error n must be a positive integer >=2\n");

}while ((nval != 2 || A < 0) || n < 2);
if (nval == 2)
        {
            do {
            //THIS has to be error
                newVal=1;
                for (i = 0; i <1/n ; i++) {
                    iterate = iterate * newVal; // these two lines iterate=iterate since oldval = 1
                }

                newVal = (1 / n) * ((n - 1) * oldVal + (A / iterate));
                delta = oldVal - newVal;
                if (delta < 0)
                    delta = delta * (-1);
                root = delta;
            } while (delta > 0.000001);
            printf("Given A = %lf and n = %d, root = %lf\n", A, n, root);
        }
}

1 个答案:

答案 0 :(得分:3)

像这样修复

#include <stdio.h>

int main(void){
    double A, root;
    int n, nval;

    do{
        printf("Enter real number and integer (A n):");
        nval = scanf("%lf %d", &A, &n);
        if (nval!=2){
            printf("Error Improperly Formatted Input\n");
            while(getchar()!='\n');
        } else if (A < 0)
            printf("Error: Value of A must be positive\n ");
        else if (n < 2)
            printf("Error n must be a positive integer >=2\n");
    }while(nval != 2 || A < 0 || n < 2);

    if(A == 0)
        root = 0.;
#if 0
A = x^n
x = n√A

Xk+1 = 1/n * ((n-1)* Xk + A / Xk^(n-1))
#endif
    else {
        double delta, newVal, oldVal = A / n;
        do {
            newVal = oldVal;
            for(int i = 1; i < n -1; ++i)
                newVal *= oldVal;

            newVal = (A / newVal + (n-1)*oldVal) / n;
            delta = oldVal - newVal;
            if(delta < 0)
                delta = -delta;
            root = oldVal = newVal;
        } while (delta > 0.000001);
    }
    printf("Given A = %lf and n = %d, root = %lf\n", A, n, root);
}