我正在尝试创建一个程序,该程序采用整数基数和整数指数,并将该整数乘以输入的某个幂。但是这段代码不起作用。我做错了什么?
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!");
}
}
答案 0 :(得分:2)
您的错误实际上是算法性的。
您将answer
乘以base
,exp
次,但您也可以使用初始值answer
启动base
。这意味着您的输出为base
* base
exp
。
您需要将answer
初始化为1
,或者从
for (i=1; i<=exp; i++)
到
for (i=1; i<exp; i++)
答案 1 :(得分:0)
Java已经提供了这项功能。
answer = Math.pow(base,exp);