当前位置:   article > 正文

C++中实现复数累乘_c++ complex类乘法

c++ complex类乘法

按部就班的直接结算多个复数相乘

#include <complex>
    #include <iostream>
    #include <cmath>

    using namespace std;

    int main()
    {
        int n = 3;
        complex<double> Ans1, Ans2(1.0,1.0);

        complex<double> a[n];

        a[0] = complex<double>(1.0, 1.5);
        a[1] = complex<double>(-1.0, 1.5);
        a[2] = complex<double>(1.0, -1.5);

        Ans1 = (a[0]*a[1]*a[2]);
        cout << "\nAns1 = " << Ans1;

        for (int i =0; i < n; i++) {
            Ans2 = Ans2 * a[i];
        }

        cout << "\nAns2 = " << Ans2;

        getchar();
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

改进:
C++中实现复数累乘用std::accumulate

#include <complex>
#include <iostream>
#include <cmath>
#include <algorithm> //accumulate
#include <functional> //multiplies

using namespace std;

int main()
{
    cons static int n = 3; //compiletime constant

    complex<double> a[n];

    a[0] = complex<double>(1.0, 1.5);
    a[1] = complex<double>(-1.0, 1.5);
    a[2] = complex<double>(1.0, -1.5);

    //define variables when they are needed

    //alternative 1: using std::multiplies
    auto Ans1 = std::accumulate(begin(a), end(a), complex<double>{1}, multiplies<complex<double>>{});
    cout << "\nAns1 = " << Ans1;

    //alternative 2: using a C++11 lambda
    auto Ans2 = std::accumulate(begin(a), end(a), complex<double>{1.0,0.0}, [](complex<double> a, complex<double> b) {return a*b;})
    cout << "\nAns2 = " << Ans2;
}  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28

原文链接

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/木道寻08/article/detail/818451
推荐阅读
相关标签
  

闽ICP备14008679号