gpt4 book ai didi

c - 这个流程图对吗?

转载 作者:太空宇宙 更新时间:2023-11-04 06:19:34 26 4
gpt4 key购买 nike

我开发了一个 C 程序,可以使用泰勒级数展开计算 sin 函数的值。我还为该程序绘制了流程图。源代码如下:

#include<stdio.h>
#include<math.h>

int fact(int n)
{
if(n==0)
{
return 1;
}
else
return n*fact(n-1);
}

int main()
{
int l,i,t=1;
float deg,rad,val=0;

printf("Enter degree of sin: ");
scanf("%f",&deg);

printf("Enter limit of Taylor series: ");
scanf("%d",&l);
rad = (deg*3.142857)/180;

for(i=1;i<=l;i+=2)
{
val = val + (t*pow(rad,i)/fact(i));
t = t*(-1);
}

printf("\nValue calculated by program, using Taylor Series:\n");
printf("Sin(%f) = %f\n",deg,val);
printf("\nValue calculated using library function:\n");
printf("Sin(%f) = %f\n",deg,sin(rad));

getch();
return 0;
}

程序流程图如下:
Flowchart Page:1
Flowchart Page: 2

那么这个流程图适合这个程序吗?有没有错误?我刚接触编程,不太了解如何绘制流程图。

最佳答案

使用阶乘函数的风险是它很快就会超出 int 范围。不需要幂函数或阶乘函数,因为泰勒级数的每一项都可以通过乘法和除法从前一项导出。

乘数不言自明,就是角度的平方。

除数是 i * (i - 1),即阶乘的下两项。

您会看到我已经删除了您的符号更改因子 t,因为要将前一项的符号从 neg 更改为 pos,或将 pos 更改为 neg,您只需乘以 -1 。但我什至通过使用 (1 - i) 反转 (i - 1) 的符号来删除它。

该系列的第一个术语很简单,所以我从它开始。

#include <stdio.h>
#include <math.h>

int main()
{
int n, i; // don't use `l` for a variable name
float deg, rad, radsq, val, term;

printf("Enter degree of sin: ");
if(scanf("%f", &deg) != 1) {
return 1; // or other error handling
}

printf("Enter limit of Taylor series: ");
if(scanf("%d", &n) != 1) {
return 1; // or other error handling
}
rad = deg * 3.14159265f / 180; // proper value for pi
radsq = rad * rad;

term = rad; // first term is rad
val = term; // so is series sum
for(i = 3; i <= n; i += 2) // we've done the first term
{
term *= radsq / (i * (1 - i)); // see explanation
val += term; // sum the series
}

printf("\nValue calculated by program, using Taylor Series:\n");
printf("Sin(%f) = %f\n", deg, val);
printf("\nValue calculated using library function:\n");
printf("Sin(%f) = %f\n", deg, sin(rad));

return 0;
}

关于c - 这个流程图对吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38263886/

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