Re: Facing Problem in Loop
- From: Kelsey Bjarnason <kbjarnason@xxxxxxxxxxx>
- Date: Wed, 11 Apr 2007 14:45:32 -0700
On Wed, 11 Apr 2007 14:03:42 -0700, 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.
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.?
Can any one help me to correct this program putting proper loop and
for high value power.
#include<stdio.h>
#include<conio.h>
conio.h isn't standard.
long double power(double x, double n);
double base, pwr;
long double result;
//int pwr;
void main()
main returns int. Now and forever. Always has.
{
clrscr();
No such function as clrscr() in C.
gotoxy(22,11);
No such function as gotoxy in C.
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();
No such function as getch() in C.
}
long double power(double x, double n)
{
long double res;
if (n < 0)
return 1/power(x, -n);
else if (n == 0)
Note that n is a double. Somehow I suspect at least one of these tests is
going to fail as the n you think should be, say, 0 is actually
0.0000000014376 or some such.
return 1.0;
else
res=(x*power(x,n-1));
printf("\n%60.10Lf", res);
return(res);
// return (x * power(x, n-1));
}
If I were you, I'd try changing the second parameter of power() to an
integer of some flavour. Also, %lf? I believe that should simply be %f.
According to my testing, the code - after changing n to an int - doesn't
work right. Results:
Your code: 332525673007965060202496.000000
bc: 332525673007965087890625
^^^^^^^^
I'm assuming this is the usual problem when using floating point values.
Indeed, testing it with long doubles bought another four digits of correct
answer.
.
- Follow-Ups:
- Re: Facing Problem in Loop
- From: Old Wolf
- Re: Facing Problem in Loop
- References:
- Facing Problem in Loop
- From: Vijaykumar Dave
- Facing Problem in Loop
- Prev by Date: Re: Very strange bug in C, please help
- Next by Date: Re: "data hiding" prototype code
- Previous by thread: Re: Facing Problem in Loop
- Next by thread: Re: Facing Problem in Loop
- Index(es):
Relevant Pages
|