This is just a small part of a much larger problem, but I do need to do this. This has to be done using Java for loops. I only have this so far:
public class MyClass {
public static void main(String args[]) {
System.out.println(calculateExp(3.0));
}
public static double calculateExp(double x) {
for(int i = 1; i <= 9; i = 2) {
x = x*x;
}
return x;
}
}
Edit: I also can't use any libraries other than the original, meaning I can't use the easy Math.pow().
CodePudding user response:
Java's Math.pow
will be useful (documentation)
You also should not be modifying x
as you go (since you always want the same number raised to varying powers), but rather have a separate variable to collect the sum.
In the end, it should look something like this:
public class MyClass {
public static void main(String args[]) {
System.out.println(calculateExp(3.0));
}
public static double calculateExp(double x) {
double total = 0.0;
for(int i = 1; i <= 9; i = 2) {
total = Math.pow(x, i);
}
return total;
}
}
EDIT: if you're not allowed to use Math.pow, you can calculate x^i
manually with another loop, like this:
public class MyClass {
public static void main(String args[]) {
System.out.println(calculateExp(3.0));
}
public static double calculateExp(double x) {
double total = 0.0;
for(int i = 1; i <= 9; i = 2) {
double x_to_i = 1.0;
for(int j = 0; j < i; j ) {
x_to_i *= x;
}
total = x_to_i;
}
return total;
}
}
CodePudding user response:
You can import java.lang.Math, and then use Math.pow(a, b), the code can look like this:
public static void main(String args[])
{
double a = 30;
double sum = 0;
for(int b = 1; b <= 9; b = 2) {
sum = Math.pow(a, i)
}
System.out.println(sum);
}