2016-12-03 53 views
0

我正在编写基于巧克力数学游戏的代码(http://www.joe-ks.com/Chocolate_Math.htm)。我可以让代码运行良好,除了最后一部分。Python将3位数字分成两部分

我希望输出结果是可读的,例如,“您的最终数字是533.这意味着您的原始数字是5,您的年龄是33岁。”

我无法弄清楚的是如何只打印三位数字的最后两位数字。

orig_num = int(input("Okay, tell me how many times a week you want chocolate. It should be more than one, but less than 10: ")) 

    guess = ((orig_num * 2) + 5) * 50 

    birthday = input("Have you had your birthday this year? Y/N: ") 
    if birthday == 'Y': 
     guessb = guess + current_year - 250 
    elif birthday == 'N': 
     guessb = guess + current_year - 251 

    year = int(input("What year were you born? (Don't worry, I won't look): ")) 
    less_year = guessb - year 

    print("Well! Your number is {}. That means your original number was {}, and you are {} years old".format(less_year, orig_num, less_year)) 

我感觉好像我应该在这里某个地方有一个功能,但我太绿了,不知道在哪里。

回答

0

你有多种方式来解决这个问题 - 一个是使用模数,即533%100=33或者你可以把它作为一个字符串的选择最后2位数字str(533)[-2:]

+0

模量工作!非常感谢你。 – mimc83

0

这是你想要实现的吗?不知道我真的明白你在这里想要完成什么,但是我用这种方法实现的输出似乎与你所描述的一致。

虽然,应该注意的是,由于您没有考虑月/偏移量,所以您的年龄(以年为单位)有可能会关闭。

例如对于输入:我要巧克力每周3天,我还没有过一次生日,今年诞生96年,输出是:

Okay, tell me how many times a week you want chocolate. 
It should be more than one, but less than 10: 3 

Have you had your birthday this year? Y/N: N 
What year were you born? (Don't worry, I won't look): 1996 
Well! Your number is 319. That means your original number was 3, and you are 19 years old 

这应该是20;)

我假设这是250251是为什么,在这种情况下,他们应该切换?再次,不知道从现在开始他们是神奇的数字。

orig_num = int(input("Okay, tell me how many times a week you want chocolate. It should be more than one, but less than 10: ")) 

guess = ((orig_num * 2) + 5) * 50 
current_year = 2016 
birthday = input("Have you had your birthday this year? Y/N: ") 
if birthday == 'Y': 
    guessb = guess + current_year - 250 
elif birthday == 'N': 
    guessb = guess + current_year - 251 

year = int(input("What year were you born? (Don't worry, I won't look): ")) 
less_year = guessb - year 
orig_num = (less_year - orig_num) // 100 
age = less_year % 100 

print("Well! Your number is {}. That means your original number was {}, and you are {} years old".format(less_year, orig_num, age))