user3390633
user3390633

Reputation: 1

algorithm for calculating the nth root of a number from Wikipedia

What's wrong with the bit of code below? I'm trying to write a program to calculate the nth root of a number but the output for the calculation I'm writing keeps coming back as 0. I simply put the numbers in to see if I would get a result of the calculation and assign it to ans2 but only a 0 gets assigned.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

void main(){

    int n = 2;
    double A = 4.0, ans = 1.0, ans2 = 1.0, pow = 1.0;

    ans2 = (1/n)*((n-1)*ans+(A/pow));

    printf("\n%lf\n", ans2);
    printf("\n%lf\n", ans);
    printf("\n%lf\n", pow);
    printf("\n%lf\n", A);
    printf("\n%d\n", n);
}

Upvotes: 0

Views: 90

Answers (1)

Byte Lab
Byte Lab

Reputation: 1626

You have to either:

  1. Write the ans2 equation as ans2 = (1.0/n)*((n-1.0)*ans+(A/pow));
  2. Declare n as a double.

With the way you have it written, the compiler will interpret 1/n as a signed integer. In integer form, 1 is just:

00000000000000000000000000000001

So when you divide it by any positive integer n > 1, it will just right shift that least significant bit off of the end, causing the result to get truncated to 0.

Upvotes: 1

Related Questions