Pyhon:不使用内置功能二进制计数 [英] Pyhon: Binary Counting without using inbuilt functions

查看:113
本文介绍了Pyhon:不使用内置功能二进制计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近具有创建二进制从1数到所选号码的程序有些麻烦。

I have been having some trouble recently with creating a program that counts in binary from 1 to the chosen number.

这是我的code的时刻:

This is my code at the moment:

num6 = 1
binStr = ''
num5 = input('Please enter a number to be counted to:')
while num5 != num6:
    binStr = str(num6 % 2) + binStr
    num6 //= 2

    num6 = num6 + 1

print(binStr)

例如,如果我输入5,它需要去1,10,11,100,101。
我似乎无法得到它的窍门。任何帮助将pciated AP $ P $,谢谢。

For example, if I input 5, it needs to go 1, 10, 11, 100, 101. I just can't seem to get the hang of it. Any help will be appreciated, thanks.

推荐答案

的问题是,你正在分裂NUM6有无关,与输入的号码。你把多少次,所以只要除以二num5和取余数,你不需要保持计数。我把你的binary_to_string在函数中,并调用它的每个号码的输入值:

The issue is that you're dividing num6 which has nothing to do with the input number. You don't need to keep count of how many times you divide so you can just divide num5 by two and take the remainder. I put your binary_to_string inside of a function and call it for each number to your input value:

num5 = int(input('Please enter a number to be counted to:'))
for i in range(num5 + 1):
    binStr = ""
    decimal_number = i
    while decimal_number > 0:
        binStr = str(decimal_number % 2) + binStr
        decimal_number //= 2
    print(binStr)

这篇关于Pyhon:不使用内置功能二进制计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆