【问题标题】:Modulo operator usage while dealing with doubles处理双打时模运算符的使用
【发布时间】:2012-07-07 23:59:35
【问题描述】:

我必须找到 (1+sqrt(3))^n 的值,其中 n

double power(double x, int y)
{
    double temp;
    if( y == 0)
       return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
       return temp*temp;
    else
    {
       if(y > 0)
           return x*temp*temp;
       else
           return (temp*temp)/x;
    }
}

现在,我无法理解如何处理模数条件。有人可以帮忙。

【问题讨论】:

    标签: c++ c modulo


    【解决方案1】:

    你不能那样做。您可以使用 fmod,但由于无法准确表示 sqrt(3),您会得到大指数的虚假值。

    我相当有信心您确实需要整数结果 ((1 + sqrt(3))^n + (1 - sqrt(3))^n),因此您应该使用整数数学,通过在每个步骤中使用模运算平方来求幂。参看。 this question

    【讨论】:

      【解决方案2】:

      这种方法是不可行的。如this question 所示,您需要比 double 类型提供的精度更高的数亿十进制数字。您实际尝试解决的问题已在here 中讨论。你们两个在同一个班吗?

      【讨论】:

        【解决方案3】:

        模需要整数类型,你可以使用 union 为你的 double 类型与整数联合使用模(如果这是 C)

        【讨论】:

          猜你喜欢
          • 2013-01-21
          • 2016-10-01
          • 2013-10-14
          • 1970-01-01
          • 2022-08-19
          • 1970-01-01
          • 1970-01-01
          • 2013-09-19
          • 1970-01-01
          相关资源
          最近更新 更多