Reputation: 33
So here is my code, I am trying to calculate the area of a wave:
public class coefficient {
public static void main (String[] args) {
double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
double T = 10;
double area = 0;
int n = 5;
double w = 2 * Math.PI / T;
for (int i = 1; i <= n; i++) {
System.out.println("n = " + i);
for (int t = 0; t < f.length; t++) {
System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
area += f[t] * Math.cos(i*(w * t));
}
System.out.printf("\nTotal Area: \t\t%.2f\n", area);
System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);
}
}
}
So my outputs are correct, except for my total and calculated areas, which are RIGHT when i=1, but after that they don't give me the right answer.
Here's the thing though - when I manually input "i":
area += f[t] * Math.cos(1*(w * t)); OR
area += f[t] * Math.cos(2*(w * t));
I get the right areas! So I think there's something wrong with my for-loop, but I'm not sure what...
So when i = 1, my area output = 15.11. That is correct. Now, when i = 2 in my loop, I SHOULD get 10.06 but instead I'm getting 25.17. I get the correct answer when I manually change i, so i isn't being defined in that line. But it is in the line above it.
Upvotes: 0
Views: 69
Reputation: 12463
Maybe it's because you aren't setting area back to 0 after each iteration. Move the declaration of area into the for
loop, and see if that workd.
double f[] = {14.0,18.7,9,4.1,6.7,6,6.3,8.4,4,2.9};
double T = 10;
int n = 5;
double w = 2 * Math.PI / T;
for (int i = 1; i <= n; i++) {
double area = 0;
System.out.println("n = " + i);
for (int t = 0; t < f.length; t++) {
System.out.println("T = " + t + " .......... " + f[t] * Math.cos(i*(w * t)));
area += f[t] * Math.cos(i*(w * t));
}
System.out.printf("\nTotal Area: \t\t%.2f\n", area);
System.out.printf("Calculated area: \t%.2f\n\n", (2/T)*area);
}
Upvotes: 2