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.
You need to read "What Every Computer Scientist Should Know About Floating-Point Arithmetic".
Floating point numbers—which are what is normally used to represent non-integers—are inherently limited. Those limits allow good performance but at the cost of such anomalies.
That's because computers can't handle real numbers properly.
http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With