Reputation: 11
I am trying to create a program that takes an integer base and integer exponent and multiply that integer to the certain power entered. But this code doesn't work. What am I doing wrong?
import java.io.*;
import java.util.Scanner;
import java.text.*;
public class Unit3_Lesson4_17 {
static Scanner in = new Scanner(System.in);
public static void main() {
Scanner scanner = new Scanner(System.in);
DecimalFormat mf = new DecimalFormat("'$'###,###,###.00");
DecimalFormat df = new DecimalFormat("#.###");
int i, exp, base, answer;
String start;
System.out.println("Hit Enter to Begin");
start = scanner.nextLine();
System.out.println("Enter the number");
base = in.nextInt();
System.out.println("Enter the exponent");
exp = in.nextInt();
answer = base;
for (i=1; i<=exp; i++) {
answer = answer * base;
}
System.out.println("The answer is " + answer);
System.out.println("This program is over!");
}
}
Upvotes: 1
Views: 407
Reputation: 10945
Your error is actually algorithmic in nature.
You are multiplying answer
by base
, exp
times, but you also start answer
with an initial value of base
. This means your output is base
*base
exp
.
You need to either initialize answer
to 1
, or change your for loop from
for (i=1; i<=exp; i++)
to
for (i=1; i<exp; i++)
Upvotes: 2
Reputation: 882
Java already provides this functionality.
answer = Math.pow(base,exp);
Upvotes: 0