C++ C+中的溢出+;

C++ C+中的溢出+;,c++,overflow,C++,Overflow,所以 代码如下: #include <iostream> #include <limits> #include <math.h> using namespace std; int main() { unsigned long long i,y,n,x=45; unsigned long long factorial = 1; for(n = 0; n <= 5; n++) { y = (pow(-1,n

所以

代码如下:

#include <iostream>
#include <limits>
#include <math.h>
using namespace std;

int main()
{
    unsigned long long i,y,n,x=45;
    unsigned long long factorial = 1;

    for(n = 0; n <= 5; n++)
    {
        y = (pow(-1,n)*pow(x,2*n)) / factorial;
        cout << "COS IS " << y << endl;
    }

    for(int i = 1; i <=n; i++)
    {
        factorial *= 2*i;
    }

}
#包括
#包括
#包括
使用名称空间std;
int main()
{
无符号长i,y,n,x=45;
无符号长阶乘=1;

对于(n=0;n要进行这类数学运算,需要使用浮点,如
float
double
而不是整型,如
long
int
long
,因为sin和cos都可以返回负数,所以不应该使用
无符号的

有很多问题美国

  • 当您应该使用浮点类型时,您可以使用整数类型
  • 对有符号计算使用无符号类型
  • 不使用弧度,而是使用度(45°≈ 0.78539弧度)
  • 你不计算循环中的阶乘,它总是1,你只在循环结束时计算它,但是太晚了,你对阶乘的计算是错误的
  • 该算法是错误的,它只是没有做麦克劳林的therorem说,你需要总结的条款,但你只是打印条款
  • 你可能想要这个:

    #include <iostream>
    #include <cmath>
    
    using namespace std;
    
    long factorial(int n)
    {
      long result = 1;
      for (int i = 1; i <= n; i++)
        result *= i;
      return result;
    }
    
    int main()
    {
      double x = 0.785398163397448309616;  //PI/4 expectd result COS(PI/4) = 0.7071067
    
      double mycosinus = 0;
      for (int n = 0; n <= 5; n++)
      {
        mycosinus += (pow(-1, n) * pow(x, 2 * n)) / factorial(2*n);
        cout << "COS IS " << mycosinus << endl;
      }
    }
    
    #包括
    #包括
    使用名称空间std;
    长阶乘(整数n)
    {
    长期结果=1;
    
    对于(int i=1;我请在问题中发布你的代码,而不是作为外部链接使用
    double
    而不是
    long
    。但是你的算法是错误的。哦,顺便说一句,你需要使用弧度而不是degrées。45^32是79946681398258369524447459012256819248199462890625。它是176个二进制数字长。我确实给了一个链接这是因为stack想重新格式化代码,而我没有耐心这么做。算法出了什么问题?
    int main()
    {
      int n = 5;
      int factorial = 1;
      for (int i = 1; i <= n; i++)
      {
        factorial *= 2 * i;
      }
    
      cout << "factorial 5 = " << factorial << endl;
    }