java program that elevates 100 numbers to the cube

-1
package pow;
import java.util.*;
/**
 *
 * @author Cuenta Casa
 */
public class Pow {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
        int num;
        do{
           System.out.print("Introduce un numero entero >=0 ");
           num = sc.nextInt();
        }while(num<0);
        System.out.println("3 ^ " + num + " = " + potencia(num));
    }
    public static double potencia(int n){
           if(n==0)   //caso base
              return 1;
           else
              return 3 * potencia(n-1);   
    }

}'introducir 

the code here '

    
asked by Raulin253 29.10.2017 в 01:08
source

1 answer

1

You can use the pow method % of class Math to calculate any power.

Let's see a program with a method:

calcularPotencia(int intValor, int intPotencia)

You will receive two parameters, the value and the power you want to calculate.

This would be the code:

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        String strMensaje = "Escriba un número: ";
        for (int i = 0; i < 100; i++) {
            System.out.print(strMensaje);

            while (!input.hasNextInt()) {
                strMensaje = "No escribió un número. Escriba un número: ";
                System.out.print(strMensaje);
                input.next();
            }
            int intValor = input.nextInt();
            if (intValor == 0) {
                strMensaje = "El número debe ser mayor que 0. Escriba un número: ";

                i = i - 1;
            } else {
                strMensaje = "Escriba un número: ";
                calcularPotencia(intValor, 3);
            }
        }
        input.close();

    }

    public static void calcularPotencia(int intValor, int intPotencia) {

        double dblPotencia = Math.pow(intValor, intPotencia);
        System.out.println("Potencia " + intPotencia + " de " + intValor + " es " + dblPotencia);

    }

}

Example of the result:

Escriba un número: 27
Potencia 3 de 27 es 19683.0
Escriba un número: a
No escribió un número. Escriba un número: 90
Potencia 3 de 90 es 729000.0
Escriba un número: 0
El número debe ser mayor que 0. Escriba un número: 43
Potencia 3 de 43 es 79507.0
    
answered by 29.10.2017 в 02:33