首页 > 解决方案 > 如何生成具有用户输入的位数的随机数?

问题描述

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

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

我这样做如下所示:

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())

我怎样才能自动化这个过程,这样我就不必在数字增加时手动添加数字?

标签: pythonrandominfinite

解决方案


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

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

所以它看起来像这样

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

推荐阅读