C++中实现复数累乘

C++中实现复数累乘按部就班的直接结算多个复数相乘#include<complex>#include<iostream>#include<cmath>usingnamespacestd;intmain(){intn=3;complex<double>An…

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

#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();
    }

改进:
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;
}  

原文链接

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/10453.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注