c - Double 在递归中返回 0,但在 int 时工作正常

标签 c recursion double

我不明白为什么如果将所有 double 更改为 int 就可以正常工作,

我的 printf 语句有问题吗?

您使用 %f%lf 表示 double,对吧?

/*
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();
}

最佳答案

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

您在 printf 中使用了错误的说明符,这是一个严重的问题,因为 printf 无法转换参数。使用 %d 或将 buffer 更改为 double 。

<小时/>

作为第二个问题,您还需要在 scanf 中使用 %lf 而不是 %f,因为 a 是一个 double,而不是 float

关于c - Double 在递归中返回 0,但在 int 时工作正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12235222/

相关文章:

使用Codeblocks在Windows 7 64位上编译C程序以在Windows XP 32位上运行

c - 如何比较两个文件的字符串?

C - 我试图在递归函数中使用 fprintf 但它只打印最少的行

Java递归斐波那契值

java自动将数组大小加倍

c# - 如何使 double 正常工作? C#

c - 谁响应内存管理用malloc()

python - python 查找字符串中的连续字母

c# - 将 double 转换为 decimal 还是从 double 构造 "new"decimal 更好?

objective-c - 纯 C 语言的安全范围书签