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閱讀 483評論 0 0
  • 昨天小溝背一日游,為了滿足兜兜的愿望。走之前講了愚公的故事。孩子說,這個愚公太不好了,他的孩子還小呢,他怎么忍心讓...
    霞想閱讀 118評論 0 1