【问题标题】:Syntax errors while dividing integers除法时的语法错误
【发布时间】:2023-04-02 00:25:01
【问题描述】:

有没有人碰巧看到导致我拉出语法错误的一个或多个错误?

#dividing integers
first = int (input('What is your first integer '))
second = int (input('What is your second integer '))

quotient = int (input('State the quotient of', str(first) , 'divided by', str(second))
print('you said the quotient  is ', quotient)
if  quotient== first / second:
    print('you are correct')
else:
    print('you are incorrect')
    print ( 'the quotient is ', first / second)

【问题讨论】:

  • 您在quotient = int(input( ... 末尾缺少最后的)
  • 尝试在您的问题中更具体。错误到底是什么意思?
  • 绝对不是print() 语句。
  • first / second 将始终导致浮动。你正在检查浮点数的 int 值。除非您将其转换为 int 并检查,否则您将永远无法获得 int 值
  • 我尝试了答案中的代码,我输入了100,然后输入了10,然后是10,程序打印了:you are correct

标签: python integer-division


【解决方案1】:

你有两个问题。一个是缺少的)。另一个是input()需要一个str参数:

#dividing integers
first = int (input('What is your first integer '))
second = int (input('What is your second integer '))

quotient = int (input('State the quotient of '+ str(first) + ' divided by ' + str(second)))
print('you said the quotient  is ', quotient)
if  quotient== first / second:
    print('you are correct')
else:
    print('you are incorrect')

【讨论】:

  • 非常感谢,非常感谢您的帮助
  • 如果您可以通过完整的错误回溯改进您的问题,我会投票赞成。
【解决方案2】:

您的代码存在一些问题:

  1. 您在商的输入语句中缺少)。你
    需要解决这个问题。

  2. 您的输入语句使用逗号。您应该改用 + 来连接输入语句中的字符串。

    '说出'+str(first)+'除以'+str(second)的商

  3. 带有if quotient== first / second: 的代码正在检查带有浮点值的整数值。

例如,如果问题是State the quotient of 3 divided by 2,而用户回答1,您的if 语句将检查如下:

if 1 == 3 / 2: 这将是 if 1 == 1.5,这永远不会正确。

你需要将方程转换为

if quotient== first // second:if quotient== int(first / second):

【讨论】:

    【解决方案3】:
    quotient = int (input('State the quotient of', str(first) , 'divided by', str(second))
    
    1. 最后你缺少')'

    2. 您正在错误地进行字符串连接。这是正确的:

      quotient = int(input('说出'+str(first)+'除以'+str(second))的商数)

    【讨论】:

      【解决方案4】:

      您的代码中有一些错误。这是其中一种工作方法。

      #dividing integers
      first = input('What is your first integer ')
      second = input('What is your second integer ')
          
      quotient = input(f'State the quotient of {first} divided by {second}')
      print('you said the quotient  is ', quotient)
      
      if float(quotient) == int(first) / int(second):
          print('you are correct')
      else:
          print('you are incorrect')
          print ( 'the quotient is ', int(first) / int(second))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-14
        • 1970-01-01
        • 2015-04-30
        • 2012-08-07
        • 1970-01-01
        • 2019-03-07
        • 2015-12-03
        • 2014-01-29
        相关资源
        最近更新 更多