如何编写一个函数,只将整数除以一个均匀分配的数字? [英] How do I write a function that will only divide an integer by a number that evenly divides into it?
本文介绍了如何编写一个函数,只将整数除以一个均匀分配的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
divide():
ran1 = randint(0, 15) #dividend
ran2 = randint(1, 15) #divisor
while ran1 % ran2 == 0: #Can I close this? Is there a better way?
divi = int(ran1 / ran2)
print('What is ' + str(ran1) + ' / ' + str(ran2) + '?')
这是我的尝试,但它不起作用。
我想要的结果如4/2或20/5
不是4/3或17/4。
This is my attempt, but it doesn't work.
I want results like 4/2 or 20/5
not 4/3 or 17/4.
推荐答案
扭转问题。从两个数字开始相乘,得到第三个数字。现在你有了所有三个值(其中两个均匀划分第三个)并可以随意做任何事情。
Reverse the problem. Start with two numbers that multiply together to get a third. Now you have all three values (two of them dividing the third evenly) and can do anything you want with them.
引用:
而ran1%ran2 == 0:#Can我关闭了吗?有更好的方法吗?
while ran1 % ran2 == 0: #Can I close this? Is there a better way?
使用模运算符(%
)的表达式是正确的。 而
是没有意义的。
[更新]
试试这段代码
The expression using the modulo operator (%
) is correct. The while
is pointless.
[update]
Try this code
from random import randint
for x in range(0,100):
ran1 = randint(0, 15)
ran2 = randint(1, 15)
if ran1 % ran2 == 0:
print(str(ran2) + " divide exactly " + str(ran1))
else:
print(str(ran2) + " doesn't divide exactly " + str(ran1))
[/ update]
[/update]
这篇关于如何编写一个函数,只将整数除以一个均匀分配的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文