赞
踩
按部就班的直接结算多个复数相乘
#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;
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。