为什么python会向下舍入?例如-12/10 = -2

时间:2015-08-17 04:12:07

标签: python python-2.x

我在Python中看到twitter post指出-12/10 = -2。是什么导致这个?我认为答案应该(在数学上)是一个。为什么python“字面上”会这样倒圆?

>>> -12/10
-2
>>> 12/10
1
>>> -1*12/10
-2
>>> 12/10 * -1
-1

2 个答案:

答案 0 :(得分:5)

这是由于int四舍五入。 (又名Floor division

private func subscriptionNoticeWithDelegate(delegate:TTTAttributedLabelDelegate) -> TTTAttributedLabel {
  let subscriptionNotice:String = "To turn on all notifications, subscribe to our monthly " +
    "service ($0.99/month). If you have already subscribed, please restore your purchase."

  let paragraphStyle = NSMutableParagraphStyle()
  paragraphStyle.lineHeightMultiple = 1.2

  let subscriptionNoticeAttributedString = NSAttributedString(string:subscriptionNotice, attributes: [
    NSFontAttributeName: UIFont(name:"HelveticaNeue-Light", size:15)!,
    NSParagraphStyleAttributeName: paragraphStyle,
    NSForegroundColorAttributeName: UIColor.grayColor().CGColor,
  ])
  let subscriptionNoticeLinkAttributes = [
    NSForegroundColorAttributeName: UIColor.grayColor(),
    NSUnderlineStyleAttributeName: NSNumber(bool:true),
  ]
  let subscriptionNoticeActiveLinkAttributes = [
    NSForegroundColorAttributeName: UIColor.grayColor().colorWithAlphaComponent(0.80),
    NSUnderlineStyleAttributeName: NSNumber(bool:true),
  ]

  let subscriptionNoticeLabel:TTTAttributedLabel = TTTAttributedLabel(frame:CGRectZero)
  subscriptionNoticeLabel.delegate = delegate
  subscriptionNoticeLabel.numberOfLines = 0
  subscriptionNoticeLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
  subscriptionNoticeLabel.textInsets = UIEdgeInsets(top:10, left:15, bottom:0, right:15)
  subscriptionNoticeLabel.setText(subscriptionNoticeAttributedString) 
  subscriptionNoticeLabel.linkAttributes = subscriptionNoticeLinkAttributes
  subscriptionNoticeLabel.activeLinkAttributes = subscriptionNoticeActiveLinkAttributes

  let subscribeLinkRange = (subscriptionNotice as NSString).rangeOfString("subscribe")
  let subscribeURL = NSURL(string:kSubscriptionNoticeSubscribeURL)!
  subscriptionNoticeLabel.addLinkToURL(subscribeURL, withRange:subscribeLinkRange)

  let restoreLinkRange = (subscriptionNotice as NSString).rangeOfString("restore")
  let restoreURL = NSURL(string:kSubscriptionNoticeRestoreURL)!
  subscriptionNoticeLabel.addLinkToURL(restoreURL, withRange:restoreLinkRange)

  return subscriptionNoticeLabel
}

答案 1 :(得分:4)

这被称为地板划分(又称int division)。在Python 2中,这是from __future__ import division 的默认行为。在Python 3中,默认行为是使用浮点除法。要在Python 2中启用此行为,请使用以下import语句:

//

要在导入此模块的情况下使用Python 3或Python 2中的分区,请使用func saveNote(noteIndex: Int) { let note = notes[noteIndex] note.realm.write { note.title = TITLE } }

更多信息可以在Python documentation," PEP 238:更改分部操作"。