gpt4 book ai didi

c - C中如何用for循环计算中点法则黎曼和

转载 作者:太空宇宙 更新时间:2023-11-04 04:15:41 27 4
gpt4 key购买 nike

对于一项作业,我应该创建一个函数,使用四分之一圆的中点规则黎曼和来计算 PI。我无法获得正确的输出,因为我认为我的逻辑有问题。这是我的函数代码:

#include <math.h>

double circle_pi(int rectangles)
{
int radius = 2;
int i;
int width = (double)radius / (double)rectangles;
double rect_area = 0;

for(i = 1; i<= rectangles; i++)
{

int midpoint = (double)width / 2;

int height = sqrt((radius * radius) - (midpoint * midpoint));

midpoint = midpoint + width;

rect_area = (double)width * (double)height;

}

return rect_area;
}

这是主要功能:

#include <stdio.h> /* scanf, printf */

double circle_pi(int rectangles); /* Calculates PI using a quarter circle */
double leibniz_pi(int iterations); /* Calculates PI using a series */

int main(void)
{
int i; /* loop counter */

/* Print out table header */
printf("Approximations for pi\n");
printf("Iterations Circle Method Leibniz Method\n");
printf("----------------------------------------------\n");

/* Print out values for each set of numbers */
for (i = 1; i <= 1000000; i *= 10)
{
/* Calculate PI with both methods */
double pi_circle = circle_pi(i);
double pi_leibniz = leibniz_pi(i);

/* Print the results of the calculations */
printf("%10i%20.12f%16.12f\n", i, pi_circle, pi_leibniz);
}

return 0; /* Return success to the OS */
}

这是预期的输出:

Approximations for pi
Iterations Circle Method Leibniz Method
----------------------------------------------
1 3.464101615138 4.000000000000
10 3.152411433262 3.041839618929
100 3.141936857900 3.131592903559
1000 3.141603544913 3.140592653840
10000 3.141592998025 3.141492653590
100000 3.141592664482 3.141582653590
1000000 3.141592653934 3.141591653590

她是我从我的代码中得到的输出:

Approximations for pi
Iterations Circle Method Leibniz Method
----------------------------------------------
1 2.000000000000
10 0.000000000000
100 0.000000000000
1000 0.000000000000
10000 0.000000000000
100000 0.000000000000
1000000 0.000000000000

(我还没有处理其他功能,这就是为什么它是空白的)

如果问题很明显,我真的很抱歉,但我是 C 的新手,很难适应它。任何帮助将不胜感激。谢谢。

最佳答案

正如 Iguananaut 已经提到的:您应该为 circle_pi 中的所有变量使用 double 数据类型,循环的迭代器除外。你真正的错误是你忘了最后总结一下

double circle_pi(int rectangles)
{
double radius = 2.0;
int i;
double width = radius / (double)rectangles;
double rect_area = 0.0;
double midpoint, height;
// set startvalue of mipoint
midpoint = width / 2.0;

for(i = 1; i <= rectangles; i++)
{
height = sqrt((radius * radius) - (midpoint * midpoint));
midpoint = midpoint + width;
rect_area = rect_area + width * height;
}
return rect_area;
}

这会产生预期的输出:

Approximations for pi
Iterations Circle Method Leibniz Method
----------------------------------------------
1 3.464101615138
10 3.152411433262
100 3.141936857900
1000 3.141603544913
10000 3.141592998025
100000 3.141592664486
1000000 3.141592653923

关于c - C中如何用for循环计算中点法则黎曼和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52693154/

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