家庭作业援助,程序没有返回值



如果我输入的值超过2,函数taylor2不返回值时,我遇到了问题。如果我输入0-2,它会输出正确的值,但任何超过2的值,我只得到一个闪烁的下划线,没有返回任何数据。

void taylor2(double x)
 {
     double total = 1;
     int i = 0;
     int count = 1;
     double temp = 1;
     do
     {
     {
         if (i % 2 == 1)
         {
             temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
             total += temp;
         }
         else {
             temp = (pow(x, i * 2 + 2) / factorial(i * 2 + 2));
             total -= temp;
         }
     }
     count++;
     i++;

     } while (fabs(temp) >= .0001);
     cout << "The last recoreded temporary value was: "<<temp << endl;
     cout << "The computed value for cosine is :  "<< total << endl;
     cout << "It took " <<count << " values to calculate the value of the function to .0001 places"<< endl;
     cout << endl; 
 }

我怀疑factorial正在返回int。如果int是32位(非常常见),那么一旦参数达到13,factorial就会溢出(在您的情况下为i = 5)。有符号整数溢出是C++中的未定义行为。

您可以使用std::uint64_t(一个无符号的64位整数)。这将允许您评估一些较大的阶乘。

有关更多参考,请参阅在C++中计算大阶乘

更好的是,在泰勒项之间使用递推关系。

最新更新