10進数で表された値を受け取り、それを2進数で表された値に変換する関数を作成しようとしています。
引数が常に整数であると仮定します。
import math
def binary_decimal_converter(x):
binary_representation = 0
number = x
while number != 0:
n = 1
while x not in range(n,n*2):
n *= 2
binary_representation += 10**(int(math.log(n,2)))
number -= n
return binary_representation
問題:
xが以下のリストにある場合、プログラムは正常に実行されます。
[1, 2, 4, 8, 16, 32, 64, 128....]
しかし、他の番号が使用されている場合、プログラムは壊れないループでスタックします。
なぜループするのか:
while number != 0: #line 24
二度実行することはできませんか?
割り当ててnumber = x
から両方を使用します。
import math
def binary_decimal_converter(x):
binary_representation = 0
number = x
while number != 0:
n = 1
while x not in range(n,n*2): # CHANGE x TO number
n *= 2
binary_representation += 10**(int(math.log(n,2)))
number -= n
return binary_representation
指定した行でに変更x
するnumber
と動作します。x
更新されていませんnumber
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加