cosx(自定义函数)与函数(noobie)的错误结果

ewm0tg9j  于 2022-12-17  发布在  其他
关注(0)|答案(1)|浏览(124)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define PI 3.14159265

double sin1x(double converted,int i);
double cos1x(double converted,int i);
int main(){
  int r,i = 1;
  double converted,p,results,results1;
  printf("Insert degrees from 0..2π: ");
  scanf("%d", &r);
  if(r < 0 || r > 360)
  {
    printf("NOT ACCEPTABLE DEGREES\n");
    exit(0);
  }
  converted = r * PI / 180;
  printf("Conversion from degrees to rad = %.3f", converted);
  results = sin1x(converted,i);
  results1 = cos1x(converted,i);
  printf("\nsin(%d) = %.3f\n", r, results);
  printf("\nsin(%d) of c = %.3f\n", r,sin(converted));
  printf("\ncos(%d) = %.3f\n", r, results1);
  printf("\ncos(%d) of c = %.3f\n", r,cos(converted));
  return 0;
}

double sin1x(double x, int i)
{
  int j = 3;
  double sinx,numerator = x,pr;
  sinx = numerator;
  do
  {
    pr = numerator;
    numerator = pr * x * x / (j * (j - 1));
    if(i % 2 == 0)
      sinx = sinx + numerator;
    else
    {
      if(i % 2 == 1)
          sinx = sinx - numerator;
    }
      i++;
      j+=2;
    }
  while(fabs(pr - numerator) > 0.000001);
  return sinx;
}

double cos1x(double x, int i)
{
  int j = 2;
  double cosx,numerator = x,pr;
  cosx = numerator;
  do
  {
    pr = numerator;
    numerator = pr * x * x / (j * (j - 1));
    if(i % 2 == 0)
      cosx = cosx + numerator; 
    else
    {
      if(i % 2 == 1)
          cosx = cosx - numerator;
    }
    i++;
    }
  while(fabs(pr - numerator) > 0.000001);
  return cosx;
}

你好,我试着用cosx和sinx做一个程序,但由于某种原因,cosx出现了问题。我找不到任何问题,但cos的结果是错误的。我也有sin()和cos()函数来比较结果。我试着改变j或使另一个变量成为阶乘,但它没有改变任何东西。

yfjy0ee7

yfjy0ee71#

至少这些问题:

初始化错误

// double cosx,numerator = x,pr;
double cosx,numerator = 1.0,pr;

缺少对j的更改

// Add to `cos1x()` do loop
j += 2;

粗糙PI

没有理由不使用更精确的值。

// #define PI 3.14159265
#define PI 3.1415926535897932384626433832795

拼写

Convertion--〉转换

候选简化

double cos1x_alt(double x) {
  double xx = x * x;
  double term = 1.0;
  double sum = term;
  for (int i = 1; 1.0 + term != 1.0; i += 2) {
    term *= -xx / (i * (i + 1));
    sum += term;
  }
  return sum;
}

相关问题