Please support our C++ advertiser: Programming Forums
Views: 1863 | Replies: 13
![]() |
•
•
Join Date: Jun 2005
Location: Cambridge, MA
Posts: 1,330
Reputation:
Rep Power: 7
Solved Threads: 44
•
•
Join Date: Jun 2005
Location: Cambridge, MA
Posts: 1,330
Reputation:
Rep Power: 7
Solved Threads: 44
An alternating series is one in which the sign flip-flops. For example,
4 + 4/3 + 4/5 + 4/7 + 4/9 + 4/11 + 4/13
is not an alternating series. But the following is:
4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13
I think the original poster wants to take a vector containing
[ a b c d e f g h ... ]
and compute
a - b + c - d + e - f + g - h + ...
4 + 4/3 + 4/5 + 4/7 + 4/9 + 4/11 + 4/13
is not an alternating series. But the following is:
4 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + 4/13
I think the original poster wants to take a vector containing
[ a b c d e f g h ... ]
and compute
a - b + c - d + e - f + g - h + ...
Below is my source code but I am getting errors stating invalid conversions. Any ideas?
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <vector>
using namespace std;
double alternating_sum(vector<double>);
int main()
{
double num_values = 0;
while (true)
{
cout << " Enter a real number (CTRL-D to quit): ";
cin >> num_values;
}
vector<double> num_sum(num_values);
double altsum_of_vector = 0;
altsum_of_vector = alternating_sum(num_sum);
cout << " The alternating sum of the vector is " << altsum_of_vector << endl;
return 0;
}
double alternating_sum(vector<double> v)
{
double sum = 0;
if (v.size() == 0)
{
return 0;
}
else
{
for (int i = 0; i < v.size(); i++)
{
if ( (i % 2) == 0)
{
sum += v[i];
}
else
{
sum -= v[i];
}
}
}
return sum;
}
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <vector>
using namespace std;
double alternating_sum(vector<double>);
int main()
{
double num_values = 0;
while (true)
{
cout << " Enter a real number (CTRL-D to quit): ";
cin >> num_values;
}
vector<double> num_sum(num_values);
double altsum_of_vector = 0;
altsum_of_vector = alternating_sum(num_sum);
cout << " The alternating sum of the vector is " << altsum_of_vector << endl;
return 0;
}
double alternating_sum(vector<double> v)
{
double sum = 0;
if (v.size() == 0)
{
return 0;
}
else
{
for (int i = 0; i < v.size(); i++)
{
if ( (i % 2) == 0)
{
sum += v[i];
}
else
{
sum -= v[i];
}
}
}
return sum;
}
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)






Linear Mode