Hello, I'm trying to come up with a little calculator for a specific equation that has to do with sigma. SQRT(r^2-x^2), where r is a constant (input as radius) and x=(1, 2,... r).
For example, if r=3,
⌊SQRT(3^2-1^2)⌋+⌊SQRT(3^2-2^2)⌋+⌊SQRT(3...
#include <iostream>
usingnamespace std;
#include <cmath>
int main()
{
cout<<"Radius: ";
int r;
cin>>r;
for(int x=1;x<=r; x++){
int rad[r]; // <== standard C++ does not allow
// non constant size while declaring array
rad[r]=x; // <== in EACH iteration assign a new
// value to element outside the array
int p; // declare p as int but assign double value
// so the result is rounded down
p=sqrt(r^2-(rad[(r)])^(2)); // Again rad[r] is outside the array
cout<<p<<endl;
}
}
I'm trying to ignore all the code, and look only at the question.
As I understand things, the program needs to find the sum of the terms of the series sqrt(r² - x²) where r is an integer, and x takes the values from 1 to r-1. (When x is equal to r, the term becomes zero).
e.g. when x = 3,
sqrt(3² - 1²) + sqrt(3² - 2²)
Now for correct calculation, floating point numbers must be used (type double) but both r and x are integers. Though I could have just used double throughout, I decided to explicitly make use of the appropriate types.
#include <iostream>
#include <iomanip>
usingnamespace std;
#include <cmath>
int main()
{
cout << "Radius: ";
int r;
cin >> r;
double total = 0;
cout << fixed;
for (int x=1; x<r; x++)
{
double xd = x;
double rd = r;
double term = sqrt(rd*rd - xd*xd); // calculate current term of series
total += term; // add it to the total
cout << setw(3) << x << " term = " << setw(8) << term
<< " total: " << setw(8) << total << endl;
}
}
Output:
Radius: 7
1 term = 6.928203 total: 6.928203
2 term = 6.708204 total: 13.636407
3 term = 6.324555 total: 19.960962
4 term = 5.744563 total: 25.705525
5 term = 4.898979 total: 30.604505
6 term = 3.605551 total: 34.210056
Chervil, thanks for the code. Your interpretation of my sum is correct, except that x takes values from 1 to r. But that's not very important. The code is great! But I've one more question to ask, though, how do I set the code in such a way where the value of each sqrt is rounded down before addition to the next sqrt? For example, before term1 is rounded down to 6 before addition to term2 which is also rounded down to 6, and so on.