Vijaykumar Dave wrote:
> I have a program for base X power N as under. The problem is that when
> the range specified in loop is given it works well, but when any
> character is pressed, it goes to infinite loop.
If you remove the nonstandard implementationspecific conio junk,
fix the illegal return type on main,
fix the incorrect "%d" specifier,
provide a '\n' to terminate the last line of output,
and fflush(stdout) after your prompts, you may find your problems disappear.
Of course, you still have the problem of detecting nonintegral values
for n, since you have no terminating condition for 0 < n < 1. This will
obviously mean power never ends.
(and don't use tabs or // comments in posted programs, unless you want
them to be unreadable)
> Second problem is it works fine for smaller value of X or N but not
> for higher say base 15 power 20. How can I get true value displayed
> with such higher base or power.?
The equivalent
return (n < 0) ? 1/power(x,n) : (n == 0) ? 1 : x*power(x,n1);
has been tested and found to work fine for power(15,20).
You might try a little easier to read output.
#include <float.h> and instead of
> printf("Result of Base %f having power %d is\n %60.10Lf.", base,
> pwr, result);
try
printf("power(%g,%g) = %.*Lg\n", base, pwr, LDBL_DIG, result);
How do you know the result was wrong?
By the way, your variables result and res are typing practice and not
needed.
> Can any one help me to correct this program putting proper loop and
> for high value power.
>
> #include<stdio.h>
> #include<conio.h>
>
> long double power(double x, double n);
>
> double base, pwr;
> long double result;
> //int pwr;
>
> void main()
> {
> clrscr();
> gotoxy(22,11);
> printf("Enter Base Number : ");
> scanf("%lf", &base);
> gotoxy(22, 13);
> printf("Enter Power Number : ");
> scanf("%lf", &pwr);
> printf("%lf %lf", base,pwr);
>
> result=power(base,pwr);
> gotoxy(22, 15);
> printf("Result of Base %f having power %d is\n %60.10Lf.", base,
> pwr, result);
> getch();
> }
>
> long double power(double x, double n)
> {
> long double res;
> if (n < 0)
> return 1/power(x, n);
> else if (n == 0)
> return 1.0;
> else
> res=(x*power(x,n1));
> printf("\n%60.10Lf", res);
> return(res);
> // return (x * power(x, n1));
> }
>
