我目前正在开发一个计算某些数字的幂的程序。数量限制为 1 到 9。我的代码发布在下面。我有以下问题:
每次我运行该程序时,它都不会打印正确的答案。
我想修改代码,以便应用程序计算 X 的 Y 次方,其中 X 和 Y 允许为 1 到 9 范围内的整数(包括 9)。如果用户输入无效值,程序应要求用户再次输入。当用户输入底数和指数值后,程序将打印结果。
这个任务的条件是我必须使用循环来计算结果 多次乘法;我不被允许使用任何可用的方法或 API 为我计算结果。请帮我想出解决方案。
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package exponent;
//import java.util.Scanner;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int b,e;
System.out.println("Enter the base");
b = Integer.parseInt(br.readLine());
System.out.println("Enter the power");
e = Integer.parseInt(br.readLine());
int t = 1;
for(int i = 1;i <= e; i++);
{
t=t*b;
}
System.out.println(t);
}
// TODO code application logic here
}
最佳答案
首先,for 循环后面不应该有分号:
for(int i=1;i<=e; i++ )
{
t=t*b;
}
一个简单的输入测试可能是这样的:
public boolean testInput(int e)
{
if(e>9||e<1)//where e is the inputted number
{
return false
}
else
{
return true;
}
}
然后像这样使用它:
boolean valid = false;
while(valid!=true)
{
e = Integer.parseInt(br.readLine());
if(testInput(e)==false)
{
System.out.println("Please enter a number between 1 and 9")
continue;
}
else
{
valid = true;
}
}
关于java - 如何用循环计算指数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19984703/