Reputation: 21
I've been stuck on this code for a couple of hours.
The sum is S = 1-x + x^2 - x^3 + x^4
.
We ask for X
and N
with starting value of i = 0
.
Whenever the previous exponent (i
) is odd we add x^i
, and
if the previous exponent is even we subtract x^i
.
I've put them on a loop but i can't seem to get the sum correctly.
Can anyone tell me what I'm doing wrong?
Thank you!
import java.util.Scanner;
public class hw1 {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int X = scan.nextInt();
System.out.println("Enter number N");
int N = scan.nextInt();
int sum = 0;
for (int i = 0; i <= N; i++) {
if (i < N) {
if (i % 2 != 0) // if I is even
{
sum = sum - (X ^ i);
} else // if I is odd
{
sum = sum + (X ^ i);
}
}
}
System.out.println("Z is " + sum);
}
}
}
Upvotes: 0
Views: 60
Reputation: 3625
So I fixed a few things in your code:
^
operator (which, as @Nick Bell pointed out, is a bitwise exclusive OR) for Math.pow
.x
and n
. In Java, convention is to give variables names that start with lower-case. Upper-cases (X
and N
) are reserved for constants (fields marked final
) and for classes (as opposed to objects). Note that this is only a convention, and that the code works fine both ways. It just helps in reading the code.x % 2 == 0
is true
for even numbers.sum
were inverted. Compare with the description of your problem in the first paragraph of your question, you'll see where you went wrong.if i < N
check was redundant. It you really wanted to limit computation to i < N
, you should specify it directly in your first for loop.x
and n
to 0
is now redundant, since your code is guaranteed to assign them another value right away.This is the updated code.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int x = 0;
while (true) {
try {
x = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
System.out.println("Enter number N");
int n = 0;
while (true) {
try {
n = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
double sum = 0;
for (int i = 0; i <= n; i++) {
if (i % 2 == 0) // if I is even
sum = sum + Math.pow(x, i);
else // if I is odd
sum = sum - Math.pow(x, i);
}
System.out.println("Z is " + sum);
}
}
Upvotes: 1