首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我的脚本不能正常工作,但我相信代码是正确的

我的脚本不能正常工作,但我相信代码是正确的
EN

Stack Overflow用户
提问于 2020-09-20 09:44:01
回答 2查看 46关注 0票数 0

我不明白为什么我的脚本不能工作!有人能帮帮忙吗!我这样做是为了我的CS课程。代码如下:

代码语言:javascript
复制
feet1 = int(input('Enter the Feet: '))
inches1 = int(input('Enter the Inches: '))
feet2 = int(input('Enter the Feet: '))
inches2 = int(input('Enter the Inches: '))

feet_sum = (feet1 + feet2)
inches_sum = (inches1 + inches2)

def check(inches_sum, feet_sum):
    while True:
        if (inches_sum) > 12:
            inches_sum -= 12
            feet_sum += 1
            return feet_sum
            return inches_sum
            break

check(inches_sum, feet_sum)

print('Feet: {} Inches: {}'.format(feet_sum, inches_sum))

更新:这行得通吗?我非常确定它应该接受变量并检查英寸是否在循环中超过12,当英寸不超过12时,它将中断循环。这有意义吗?

代码语言:javascript
复制
feet1 = int(input('Enter the Feet: '))
inches1 = int(input('Enter the Inches: '))
feet2 = int(input('Enter the Feet: '))
inches2 = int(input('Enter the Inches: '))

feet_sum = (feet1 + feet2)
inches_sum = (inches1 + inches2)

def check(inches, feet):
    while True:
        if (inches_sum) > 12:
            inches_sum -= 12
            feet_sum += 1
        else:
            break

check(inches_sum, feet_sum)

print('Feet: {} Inches: {}'.format(feet_sum, inches_sum))
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-09-20 09:58:19

我想这就是你想要的:

代码语言:javascript
复制
feet1 = int(input('Enter the Feet: '))
inches1 = int(input('Enter the Inches: '))
feet2 = int(input('Enter the Feet: '))
inches2 = int(input('Enter the Inches: '))

feet_sum = (feet1 + feet2)
inches_sum = (inches1 + inches2)

def check(inches_sum, feet_sum):
    while (inches_sum) >= 12:
        inches_sum -= 12
        feet_sum += 1
    return inches_sum, feet_sum

inches_sum, feet_sum = check(inches_sum, feet_sum)

print('Feet: {} Inches: {}'.format(feet_sum, inches_sum))

结果:

代码语言:javascript
复制
Enter the Feet: 1
Enter the Inches: 26
Enter the Feet: 1
Enter the Inches: 26
Feet: 6 Inches: 4
票数 0
EN

Stack Overflow用户

发布于 2020-09-20 10:02:54

在没有函数的情况下会这样做,否则需要处理返回值。也可以使用while而不是if来使其更健壮:

代码语言:javascript
复制
feet1 = int(input('Enter the Feet: '))
inches1 = int(input('Enter the Inches: '))
feet2 = int(input('Enter the Feet: '))
inches2 = int(input('Enter the Inches: '))

feet_sum = (feet1 + feet2)
inches_sum = (inches1 + inches2)

while (inches_sum) > 12:
  inches_sum -= 12
  feet_sum += 1

print('Feet: {} Inches: {}'.format(feet_sum, inches_sum))

此外,负数不会被处理,这将作为一项练习留给您:)

一切正常后,您可以尝试将其提取为一个函数,如Steve的答案所示。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63974825

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档