gpt4 book ai didi

在 C 中创建一个 sin 公式

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

程序可以编译,但在运行时我没有从我的输入中得到正确的值。我一直在寻找一种制作正弦公式的方法并找到了这个公式,但我认为它不正确。

我的公式正确吗?我认为仅在 C 中运行 sin 函数也会给我错误的值。

更新:如果我输入 1.5 和 4,我仍然得到这些更改的错误值。我得到 0.000 和一个随机整数

 /*
* Function mySin is using a sin formula to get the sin of x
* the function then returns the sin value computed
* Parameters -for function mySin are "x" is the value for sin
* -"n"is the number of series to run
*
*The program also uses the sin(x) function to get the real sin
*
*/

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

int mySin(double x, int n){

int i=0;
double sinx=0;

for(i=1; i<=n; i+=2){
sinx=(pow(x,i)+sinx); //
}

return sinx;
}


int main(double sinx){

double realSin=0;

double x=0;
int n=0;

printf("Please input x and n:");
scanf("%lf",&x);
scanf("%d",&n);

mySin(x,n);

realSin=sin(x);

printf("mySin= %f\n sin=%d\n",sinx,realSin);
}

最佳答案

您的 mySin 函数至少在 5 个不同的方面是错误的。用**表示求幂(避免和xor混淆),正确的公式是

sin(x) = x - x**3/3! + x**5/5! - x**7/7! + x**9/9! ...

您的实现失败是因为

  1. 它会在循环的每次迭代中丢弃之前的项。
  2. 它不会改变符号。
  3. 它包括偶数指数项。
  4. 它不计算除数的阶乘。
  5. 返回类型为int,舍去计算结果的小数部分。

此外,main 在其他几个方面是错误的。 mySin 的返回值被完全忽略。相反,sinxmain 的第一个参数,它是程序收到的命令行参数的数量(包括它运行的名称)。此外,%d 用于格式字符串中的所有数字,无论类型如何,当它仅用于 int 时。

要修复 mySin,让 i 仅遍历奇数,并让循环的每次迭代都计算 x**i/i! 并将其添加到 sinx 的当前值中。

要修复 main,请在 main 中声明一个局部 sinx 变量并赋值 sinx = mySin(x, n) 而不是将 sinx 声明为参数。此外,使用 %lf 通过 scanf 读取 double ,使用 %f 通过 printf 写入 double 。

关于在 C 中创建一个 sin 公式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22522857/

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