Write a program that computes XN where X is a floating point number and N is a positive integer. The program
informs the user that N must be positive if the user enters a negative value. Of course,
XN = X * X * X * ... * X
--------------------
N times
The user dialog will look something like this:
Enter X
1.3
Enter N
5
1.3 raised to the power 5 is: 3.71293
-------
Enter X
5.6
Enter N
-3
N must be a positive integer.
I ended with these but the else statement executes an error:
import java.io.*;
import java.util.Scanner;
public class TryChap5Exer3 {
public static double power(double x, double n) {
if (n==0) {
return 1;
} else {
return x*power(x, n-1);
}
}
public static void main(String[] a) {
Scanner scan = new Scanner(System.in);
double x = 0.0d;
int n = 0;
System.out.println("Enter X");
x = scan.nextDouble();
System.out.println("Enter N");
n = scan.nextInt();
if (x<0) {
System.out.println("N must be a positive integer.");
} else {
System.out.println(x + "raised to the power " + n + " is: " + power(x,n));
}
}
}
and also this prob:
Page 12 of 12
Here, avg is the average of the N numbers, and avg2 is its square.
avgSquare is the average of Xi * Xi. In other words, this is the average of the squared value of each floating
point number.
For example, if N = 4, say the numbers were:
Xi Xi * Xi
2.0 4.0
3.0 9.0
1.0 1.0
2.0 4.0
sum 8.0 18.0
Now:
avg = 8.0/4 = 2.0
avg2 = 4.0
avgSquare = 18.0/4 = 4.5
SD = Math.sqrt( 4.5 - 4.0 ) = Math.sqrt( .5 ) = 0.7071067812
To do this you will need to do several things inside the loop body for each floating point value as it comes in:
add it to a sum, square it and add it to a sum of squares. Then after the loop is finished apply the formula.
I dont have yet the codes for this because I will try the second one later..But thanks in advance