【问题标题】:How to generate a random number with the amount of digits, the user enters?如何生成具有用户输入的位数的随机数?
【发布时间】:2021-12-18 04:02:52
【问题描述】:

我正在制作一个用于练习的小型数学程序。

用户应该输入,两个和应该有多少位数。

如下图所示:

import random
digits = int(input("How many digits should the numbers have? "))
if digits == 1:
    while True:
        num1 = random.randint(0,9)
        num2 = random.randint(0,9)
        solution = num1 + num2
        print(str(num1) + " + " + str(num2) + " = ? ")
        question = int(input())

如何使流程自动化,这样我就不必在数字增加时手动添加数字?

【问题讨论】:

    标签: python random infinite


    【解决方案1】:

    我可能认为有更好的选择,尤其是类型转换较少的情况,但在我的脑海中,这将是获得 n 位数字的选项:

    import random
    digits = int(input("How many digits should the numbers have? "))
    
    list = []
    for _ in range(digits):
        list.append(str(random.randint(0,9)))
                    
    number = int("".join(list))
    

    也就是说,只要在 Stack Overflow 上进行简短搜索,就有 even cleaner options 可用。

    【讨论】:

      【解决方案2】:

      random.randint 包括两个边界,所以我认为您的示例中的意思是 random.randint(0, 9)。

      我建议使用数学来解决您的问题。 n 位数字是介于 10**(n-1) 和 10**n 之间的数字。

      所以它看起来像这样

      digigts = int(digits)
      num = random.randint(10**(digits - 1), 10**digits - 1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多