2

我是新的 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);
        }
    }
}

我在让它工作方面没有任何成功(虽然它适用于浮动)。我究竟做错了什么?(顺便说一句,我正在使用带有编译器的代码块。)

4

1 回答 1

5

您忘记在函数中添加return语句。approx1()如果没有该return语句,如果您使用返回的值,它会调用未定义的行为

报价C11标准,第 6.9.1 章

如果}到达终止函数的 ,并且调用者使用函数调用的值,则行为未定义。

于 2015-09-25T22:17:22.347 回答