python - 如何生成具有用户输入的位数的随机数?
问题描述
我正在制作一个用于练习目的的小型数学程序。
用户应该输入两个加数应该有多少位数。
我这样做如下所示:
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())
我怎样才能自动化这个过程,这样我就不必在数字增加时手动添加数字?
解决方案
random.randint 包括两个边界,所以我认为你的意思是 random.randint(0, 9) 在你的例子中。
我建议使用数学来解决您的问题。n 位数字是 10**(n-1) 和 10**n 之间的数字。
所以它看起来像这样
digigts = int(digits)
num = random.randint(10**(digits - 1), 10**digits - 1)
推荐阅读
- regression - 如何处理缺乏经验的客户满意度分数作为缺失值?
- ios - Swift交替UITableViewCell渐变颜色
- python - 在 Python 中以特定间隔将数据附加到 DataFrame
- typescript - 用打字稿正确使用黄瓜?
- jekyll - jekyll 中的单反引号内联代码块,选择语言
- javascript - 将 Google 云端硬盘内容流式传输到 Chromecast
- office-js - 如何使用。officejs中的Isempty
- c++ - &C::c 和 &(C::c) 有什么区别?
- excel - 如何找到为主变量的子变量编码 Y 或 N 的变量的计数?
- css - 带有svg的关键帧动画