i new c programmer , working on school project have approximate value or pi. professor stated have declare integer terms using long double
. console shows me asking user number of terms approximate pi given function. enter 1 number of terms 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; <= 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 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 correct input\n"); scanf("%d", &terms); } } }
i haven't had success in getting work( works float though). doing wrong? (i using code blocks included compiler btw.)
you forgot add return
statement in approx1()
function. withoout return
statement, if make use of returned value, invokes undefined behavior.
quoting c11
standard, chapter §6.9.1
if
}
terminates function reached, , value of function call used caller, behavior undefined.
Comments
Post a Comment