【问题标题】:Sine series equation not calculating properly正弦级数方程计算不正确
【发布时间】:2019-04-01 19:26:24
【问题描述】:

我在我的代码中找不到逻辑错误。 整个事情在数学上是错误的吗? 还是部分正确。

float x,term,fx;
int i, nterms;
cin>>x>>nterms;
for(i=1;i<=nterms;i+=2){ 
term=1;
fact=1;
for(j=1;j<=i;j++){
        term=term*x;
        fact=fact*j;
}
sign=-1*sign;
fx+=sign*term/fact;
}

cout << fixed << showpoint;
cout << setprecision(6);
cout<<fx;

【问题讨论】:

标签: c++


【解决方案1】:

我一步一步地修正了你的代码,我不能更进一步,因为我不确定你想在你的代码中做什么。如果您告诉我们它们是什么,我将能够修复此代码。

#include <iostream>
#include <iomanip>
#include <stdio.h>

int main() {
  long double x,term,fx, fact;
  int i, j, nterms;
  int sign;

  std::cin>>x>>nterms;
  term=1;
  fact=1;
  sign=1;
  fx = 0;
  for(i=1;i<=nterms;i+=2){ 
    for(j=1;j<=i;j++){
      term=term*x;
      fact=fact*j;
    }
    sign=-1*sign;
    fx+=sign*term/fact;
  }
  std::cout << std::setprecision( 6 )  << fx << std::endl;
}

这里有几点说明:

  1. 似乎 using namespace 用于std谨慎使用,因为某些命名空间之间可能会发生冲突。这个page(法语)建议了两个用例。

    一个。 一个一个导入符号:

    using std::cout; 
    using std::endl; 
    

    b.仅在 本地范围 中使用它们(例如在花括号块中):

    void a_function() { 
        // std will be imported only within this block 
        using namespace std;   
       cout << "hello there" << endl; // will work
    }
    
  2. 在使用变量之前声明变量。将我的答案与您的代码示例进行比较。

  3. 请注意 type 可以处理的 min 和 max 值。您的函数似乎处理非常大或小的值。我将它们的类型更改为 long double (但这只是让问题更进一步)。你有范围。看看这个SO answer。它导致limit.h,它显示了数字限制。选择最安全的值来存储您的值(或为用户输入设置最大值和最小值)。

【讨论】:

  • 符号应该确定下一个值的 + 或 - 。我被告知显示点是为了输出的准确性。
  • 也感谢您的帮助
  • 我认为在这里使用 bool 会更好。这是一种交替模式,第一项是 x-x^3/3!+x^5/5!等等
  • 布尔符号 = true; //for + and false for negative 然后使用 if else 将其实现到等式中。符号由序列中的项数决定。因此,如果 nterms=3 则符号为 - + -
  • 哦,好的,谢谢您对此的澄清。如果我的答案不清楚,也很抱歉。我不是以英语为母语的人
猜你喜欢
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 2016-06-16
  • 2015-06-20
  • 1970-01-01
  • 1970-01-01
  • 2019-08-13
  • 1970-01-01
相关资源
最近更新 更多