问题
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.)
回答1:
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.
来源:https://stackoverflow.com/questions/32791411/c-long-double-and-printf-issue