Well at least with (i*i) you wont get function overheads, and its less work to type.
This is a discussion on alternating sum within the C++ Programming forums, part of the General Programming Boards category; Well at least with (i*i) you wont get function overheads, and its less work to type....
Well at least with (i*i) you wont get function overheads, and its less work to type.
Hi all,
Thank you for all the helpful pointers. I couldn't get the sign=-sign idea to work, I guess, I have no idea how. Can somebody be more specific on how to do that?
Here's the code and the output though.. I still got warnings but it compiled anyway..
Code:#include <iostream> #include <cmath> using namespace std; int main() { double i = 0; int sum = 0, n = 0; int elements = 0; cout << "Enter a value for n where n >= 1: "; cin >> n; for (i = 1; i < n; ++i) { elements = (pow(-1.0,i-1))*(i * i); sum += elements; cout << elements << " + "; } elements = (pow(-1.0,i-1))*(i * i); sum += elements; cout << elements << " = " << sum << endl; }
Code:Enter a value for n where n >= 1: 4 1 + -4 + 9 + -16 = -10 Press any key to continue...
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Here is what I came up with. There is definitely a better way to write this but I will go for it this time. Thank you everyone, especially tabstop and iMalc.
Code:#include <iostream> #include <cmath> using namespace std; int main() { double i = 0; int sum = 0, n = 0; int elements = 0; cout << "Enter a value for n where n >= 1: "; cin >> n; for (i = 1; i < n; ++i) { elements = (pow(-1.0,i-1))*(i * i); sum += elements; if (elements % 2 != 0) cout << " + " << elements << " "; else cout << elements; } elements = (pow(-1.0,i-1))*(i * i); sum += elements; if (elements % 2 != 0) cout << " + " << elements << " = " << sum << endl; else cout << elements << " = " << sum << endl; }Code:Enter a value for n where n >= 1: 4 + 1 -4 + 9 -16 = -10 Press any key to continue...