C - long double和printf问题

Jai*_*hra 2 c printf long-double

我是新的C程序员,我正在研究一个学校项目,我必须估算值或pi.我的教授表示我们必须使用声明所有整数项long double.控制台显示我询问用户在给定函数时接近pi的项数.我输入1作为术语数,但代码返回-0.00000000而不是4.00000000.

#include <stdio.h>
#include <math.h>

long double approx1(int terms)
{
    long double pi = 0;
    long double num = 4;
    long double denom = 1;
    int i;

    for(i=1; i <= terms; i++)
    {
        if(i%2 != 0)
        {
            pi=pi+(num/denom);
        }
        else
        {
            pi=pi-(num/denom);
        }
        denom = denom + 2;
    }
     printf("%.8Lf\n", pi);
}

int main()
{
    int terms;
    long double pie;

    printf("input number of terms, input 0 to cancel\n");
    scanf("%d", &terms);

    while(terms != 0)
    {
        if(terms > 0)
        {
            pie = approx1(terms);
            printf("%.8Lf\n", pie);
            printf("GG mate\n");
            break;
        }
        else
        {
            printf("Incorrect input, please enter a correct input\n");
            scanf("%d", &terms);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我没有成功地使它工作(虽然它适用于浮动).我究竟做错了什么?(我正在使用包含编译器btw的代码块.)

Sou*_*osh 5

您忘了return在approx1()函数中添加语句.return如果您使用该语句,则如果您使用返回的值,则会调用未定义的行为.

引用C11标准,第6.9.1章

如果}终止了函数,并且调用者使用了函数调用的值,则行为是未定义的.