1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
|
#include <iostream>
#include <cmath>
using namespace std;
const double PI = 4.0 * atan(1.0);
const double mu_o = PI * 4.0e-7;
const int speedOfLight = 299792458;
const double ep_bottom = mu_o * (double)speedOfLight;
const double ep_o = 1 / ep_bottom;
double r_distance (double x_one, double y_one, double z_one) {
double x_squared = pow(x_one, 2);
double y_squared = pow(y_one, 2);
double z_squared = pow(z_one, 2);
double length = sqrt(x_squared + y_squared + z_squared);
return length;
}
int main () {
int n;
double q, x, y, z;
cout << "How many charges would you like to include?";
cin >> n;
double chargearray[n][4];
for (int assign = 0; assign < n; assign++) {
cout << "Charge (in C):";
cin >> q;
cout << "x-position (in m):";
cin >> x;
cout << "y-position (in m):";
cin >> y;
cout << "z-position (in m):";
cin >> z;
chargearray[assign][0] = q;
chargearray[assign][1] = x;
chargearray[assign][2] = y;
chargearray[assign][3] = z;
}
int i, j;
i = 0;
j = i;
double mycoolsum = 0;
while (i < n) {
while (j < n) {
if (i == j) {
j++;
}
else {
int q_first, q_second, iteration_i, iteration_j;
iteration_i = i - 1;
iteration_j = j - 1;
q_first = chargearray[iteration_i][0];
q_second = chargearray[iteration_j][0];
int q_product = q_first * q_second;
double chargeperdistance, distancebetweenpoints, distance_i, distance_j;
distance_i = r_distance(chargearray[iteration_i][1],chargearray[iteration_i][2],chargearray[iteration_i][3]);
distance_j = r_distance(chargearray[iteration_j][1],chargearray[iteration_j][2],chargearray[iteration_j][3]);
distancebetweenpoints = abs(distance_i - distance_j);
chargeperdistance = (double)q_product / distancebetweenpoints;
mycoolsum += chargeperdistance;
j++;
}
}
j = n;
i++;
}
double ep_inv = 1 / ep_o;
double pi_inv = 1 / PI;
double oneeigth = 1 / 8;
double frac = ep_inv * pi_inv * oneeigth;
double energy = frac * mycoolsum;
cout << "\n The total energy of the charge distribution is:";
cout << energy;
}
|