2016年9月9日 星期五

python 程式設計50題測試範例-50-1


50-1、試設計一程式,利用二分逼近法求一數值a之開方根。

程式:
#coding=utf8



print("50-1、試設計一程式,利用二分逼近法求一數值a之開方根。")
print("========================================================")
           
while True:
     a=int(input("請輸入數值 0 <  a  < 10000:"))
     try:
        a= int(a)
       
     except ValueError:
       print ('這是不合法的輸入.  請再輸入一次...')
       continue
        
     if ( a > 0  and a < 10000):
       break
#==================
small=float(0.0000001)
if (a<1) :
    low=0
    high=1
else:
    low=1
    high=a

while ( (high-low) > small):
   mid=float((low+high)/2)
   if (mid*mid > a):
      high=mid
   else:
      low=mid

print("一數值a之開方根: ",low)
      
    


結果:
================ RESTART: D:/程式語言 Python 入門/50題/Ex50-50-1.py ================
50-1、試設計一程式,利用二分逼近法求一數值a之開方根。
========================================================
請輸入數值 0 <  a  < 10000:5
一數值a之開方根:  2.2360679507255554
>>> 
================ RESTART: D:/程式語言 Python 入門/50題/Ex50-50-1.py ================
50-1、試設計一程式,利用二分逼近法求一數值a之開方根。
========================================================
請輸入數值 0 <  a  < 10000:10
一數值a之開方根:  3.162277616560459
>>> 
================ RESTART: D:/程式語言 Python 入門/50題/Ex50-50-1.py ================
50-1、試設計一程式,利用二分逼近法求一數值a之開方根。
========================================================
請輸入數值 0 <  a  < 10000:100
一數值a之開方根:  9.999999991618097
>>> 

沒有留言:

張貼留言

Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3

  Node-Red Dashboard UI Template + AngularJS 參考 AngularJS教學 --3 AngularJS 實例 <!DOCTYPE html> <html> <head> <meta charse...