I wrote a program to calculate the nth root of a number up to two decimal places. for example, the 4th root of 81 is 3., the 3rd root of 125 is 5. It works fine, except for the second root of 4. It gives an output of 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 tried this for a few hours but can't fix it. can anyone debug this? I'll be very grateful.
c algorithm floating-accuracy
narayanpatra
source share