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
Enter N
1.3 raised to the power 5 is: 3.71293
Enter X
Enter N
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
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

6 Years
Discussion Span
Last Post by Akill10

Your first problem is simple enough; you wrote (x < 0) where I think you meant (n < 0). Thanks for using CODE-tags, by the way; it makes it easier to help you.

For the second problem, you need to give it a try before people on Daniweb will help you. Try writing some code, and if it's not working come back with whatever you have.

Edited by mike_2000_17: Fixed formatting


I run the code of the first program and it's run on my eclipse.

in the second problem you should used a for loop until user enters all numbers and save this numbers in array of size N*2 and then calculate which you need.


Why are you using recursion? It is not needed if you only print out 1 number. All you do is create your power method, then return Math.pow(x,n). You ask for a number, then ask for the exponent, there is no recursion needed.

As was stated, you test the value of x where you should be testing n.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.