I wrote a program to calculate nth root of a number upto 2 decimal places. eg 4th root of 81 is 3., 3rd root of 125 is 5.Its working nicely except for the 2nd root of 4. It's giving the output 1.99 instead of 2. Here is the code.
#include<stdio.h>
int main(int argc, char **argv)
{
double root1(int,int);
int n;
int num1;
double root;
printf("\n\n-----------This is the programme to find the nth root of a number-----------\n\n");
printf("Enter a nuber greater then 1 : ");
scanf("%d",&num1);
if(num1>1)
{
printf("Enter the value for 'n'(the root to be calculated) : ");
scanf("%d",&n);
root = root1(num1,n);
printf("%d th Root of %d is %f\n\n", n,num1,root);
}
else
printf("wrong entry");
return 0;
}
double root1(int a, int b)
{
int j;
double i,k;
double incre = 0.01;
for(i=1; i<=a; i = i+incre)
{
for(j=0;j<b;j++)
{
k=k*i;
}
if(a<k)
{
return(i-incre);
break;
}
else
k=1;
}
}
I have tried it for hours, but can't rectify it. can anybody debug this?? I will be very thankful.
incre
to0.001
? Does that help? – Pero0.0078125
makes more sense, as that has a binary representation. – Herdouble root = pow(input, 1.0 / base)
. For instance, the 3rd root of 10 can be calculated bypow(10, 1.0 / 3)
, returning 2.15443.... If you're looking for higher accuracy, check out the formulae at en.wikipedia.org/wiki/Nth_root. – Pentathlon