gpt4 book ai didi

C - long double 和 printf 问题

转载 作者:行者123 更新时间:2023-12-02 09:31:22 24 4
gpt4 key购买 nike

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

我还没有成功地让它工作(尽管它可以与 float 一起工作)。我究竟做错了什么? (顺便说一句,我正在将代码块与附带的编译器一起使用。)

最佳答案

您忘记在 approx1() 函数中添加 return 语句。如果没有 return 语句,如果您使用返回值,它会调用 undefined behavior .

引用 C11 标准,第 §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.

关于C - long double 和 printf 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32791411/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com