2

I am new C programmer and I am working on a school project where I have to approximate the value or pi. My professor stated that we have to declare all integer terms using long double. The console shows me asking the user for the number of terms to approximate pi given a function. I enter 1 for the number of terms however the code returns -0.00000000 instead of 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);
        }
    }
}

I haven't had any success in getting it to work( it works with float though). What am I doing wrong? (I am using Code Blocks with the included compiler btw.)

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
Jai Mehra
  • 21
  • 2
  • "all integer terms using `long double`" `long double` is not an integer type. What do you mean? – too honest for this site Sep 25 '15 at 22:47
  • 1
    If your Code::Blocks IDE is using the MinGW GCC compiler (which I believe is common), you might also be running into this problem: http://stackoverflow.com/a/7136886/12711 I believe that newer versions of MinGW solve the problem by implementing custom support for `printf()` instead of relying only on using `msvcrt.dll`. So you might want to try a newer version of MinGW or MinGW-w64. – Michael Burr Sep 26 '15 at 05:56

1 Answers1

5

You forgot to add a return statement in your approx1() function. Withoout that return statement, if you make use of the returned value, it invokes undefined behavior.

Quoting C11 standard, chapter §6.9.1

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261