[英]Print the digits of a 3-digit number in order
I am currently trying to create a program that requests a 3 digit number from the user and prints out the individual digits of the number in order, eg: 我目前正在尝试创建一个程序,该程序向用户请求一个3位数字,并按顺序打印出该数字的各个数字,例如:
"Input 3 digits: 123"
1
2
3
I am not allowed to use any form of strings, just mathematical operations. 我不允许使用任何形式的字符串,只能使用数学运算。
Also, I have gotten formulas for the second and third digit but cannot get the first for the life of me, and when I run the program the first and the second digit return with a decimal number which I am not sure how to avoid. 另外,我已经获得了第二个和第三个数字的公式,但是在我生命中无法获得第一个数字,并且当我运行程序时,第一个和第二个数字返回一个十进制数,我不确定该如何避免。
My code: 我的代码:
n = eval(input('Enter a 3-digit number: '))
c = n % 10
b = n - c
b = b / 10
b = b % 10
a = n / b
a = a % 10
print(a)
print(b)
print(c)
There's a much easier way to do this that doesn't require any math. 有一种更简单的方法,不需要任何数学运算。 In Python, strings are iterable and input()
returns a string. 在Python中,字符串是可迭代的,并且input()
返回一个字符串。 So you can just do this: 因此,您可以执行以下操作:
n = input('enter a number: ')
for x in n:
print(x)
Divide your number by 100, inside of a call to int
: 在对int
的调用中,将您的数字除以100:
Input 3 digits: 435 输入3位数字:435
firstDigit = int(n / 100)
firstDigit will be 4 firstDigit将为4
You get the input as a string so, using your example, you would get '123'. 您以字符串形式获取输入,因此,使用您的示例,您将获得“ 123”。 If you're not obligated to use the formulas, you could get each digit as follows: 如果您没有义务使用公式,则可以按以下方式获得每个数字:
user_input = input('Enter a 3-digit number: ')
first_digit, second_digit, third_digit = [int(digit) for digit in user_input]
print first_digit
print second_digit
print third_digit
THe problem is where you divide n by b -- no reason to divide the original number by its second digit. 问题是您将n除以b-没有理由将原始数字除以第二个数字。 You probably wanted to divide by 10 again. 您可能想再次除以10。
It's easier if you remember that when you divide integers , you get an integer -- so, for example: 329 / 10 gives 32 That save you from having to subtract at all (also, clearer variable names make it much more readable): 如果您记得除以整数时 ,会得到一个整数,这样会更容易-例如,329/10给出32,这使您不必再进行减法运算(而且,更清晰的变量名使它更具可读性):
dig3 = n % 10
n = n/10
dig2 = n % 10
dig1 = n/10
I think you are looking for this: 我认为您正在寻找:
n = eval(input('Enter a 3-digit number: '))
c = n % 10
b = int(n / 10)
b = b % 10
a = int(n / 100)
a = a % 10
print(a)
print(b)
print(c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.