CS106A assignment3 --problem3 Exponentiation

/* TODO: Replace these file comments with a description of what your program
 * does.
 */
import acm.program.*;

public class RaiseToPower extends ConsoleProgram {
    public void run() {
        /* Sit in a loop reading bases and exponents and printing out the values
         * produced by raising the base to the exponent.
         */
        while (true) {
            double base  = readDouble("Enter base: ");
            int exponent = readInt("Enter exponent: ");
            println(base + " ^ " + exponent + " = " + raiseToPower(base, exponent));
        }
    }
    
    private double raiseToPower(double base, int exponent) {
        /* 
         * if exponent = 0,then return 1,
         * else if exponent > 1,return base^exponent,
         * else return 1/(base^exponent)
         */
        if(exponent ==0 ){
            return 1;
        }else if(exponent > 0){
            double temp = 1;
            for (int i=0;i<exponent;i++){
                temp = temp * base; 
            }
            return temp;
        }else{
            double temp = 1;
            for (int i=0 ; i<-exponent ;i++){
                temp = temp * base;
            }
            return 1/temp;
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 高考考察方向一向是我们学习的重点,今天给大家带来高考生物试题解析版本,大家可以根据自己学习的模块对应练习,看看都会...
    xiaoya99阅读 3,339评论 0 0
  • 昨天小沟背一日游,为了满足兜兜的愿望。走之前讲了愚公的故事。孩子说,这个愚公太不好了,他的孩子还小呢,他怎么忍心让...
    霞想阅读 780评论 0 1