0

I don't get why it works fine if you change all the double into int,

is there something wrong with my printf statements?

you use %f or %lf for double, right?

/*
double power(double a, int b) that calculates the power ab. You are allowed to use the
multiplication operator *.
*/
#include <stdio.h>
#include <conio.h>
double power(double a,int b)
{
    double buffer;
    if(b > 1)
    {
        buffer = a * power(a,b-1);
        return buffer;
    }
    else
        return a;
}
int main(void)
{
    double a;
    int b;
    int buffer;
    scanf("%f",&a);
    scanf("%d",&b);
    buffer = power(a,b);
    printf("%f",buffer);
    getch();
}
Bharat Sinha
  • 13,973
  • 6
  • 39
  • 63
jantristanmilan
  • 4,188
  • 14
  • 53
  • 69
  • Try `%lf` for `double`, `double` for `buffer`. – Tugrul Ates Sep 02 '12 at 10:33
  • The [answer by cnicutar](http://stackoverflow.com/a/12235250/335858answer) correctly identified two issues in your code that will make your code work, but there is a third issue that may show up when your end-users enter a very large `b`: your program may overflow stack, or take too long to produce the result, depending on the optimizer settings. You need to read about [exponentiation by squaring](http://en.wikipedia.org/wiki/Exponentiation_by_squaring) to address that problem. – Sergey Kalinichenko Sep 02 '12 at 10:47
  • If possible, you should adjust your compiler preferences (or *preference*) so that you will be warned about mismatches between types and format specifiers when possible. – eq- Sep 02 '12 at 11:26

4 Answers4

1
int buffer;
printf("%f",buffer);

You're using the wrong specifier in printf, which is a serious problem because printf cannot convert arguments. Either use %d or change buffer into a double.


As a second problem, you'll also want to use %lf instead of %f in scanf, since a is a double, not a float.

cnicutar
  • 178,505
  • 25
  • 365
  • 392
0
scanf("%f",&a);

You need to read your double by %lf. See this question for why you need %lf with scanf but not with printf.

Community
  • 1
  • 1
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
0

The thing is that on your system, int appears to be of the same length as float but not as double - when you scanf() a double, you loose half of it (and by the way, feeding a wrong format specifier to scanf is undefined behaviour). You have to use %lf for doubles.

0

you should use %lf for double in scanf See this question.
In place of:

scanf("%f",&a);

use this:

scanf("%lf",&a);

Also in the main function the type of buffer should be double not int.

Community
  • 1
  • 1
Jainendra
  • 24,713
  • 30
  • 122
  • 169