简体   繁体   English

Python 数字总和 function 在大数字上返回错误数字

[英]Python digit sum function returns wrong digits on large numbers

The function I wrote is fairly basic: It walks through every digit of num and prints it out.我写的 function 相当基本:它遍历num的每个数字并打印出来。 The remainder is then run again until the sample code is finished.然后再次运行剩余部分,直到示例代码完成。

num = 1000000000000000000000000000001
while num > 0:
    curr = num % 10
    num = (num - curr) / 10
    print(curr)

The expected output of this would be 100000000000000000000000000001 (with linebreaks in between).预期的 output 将是100000000000000000000000000001 (中间有换行符)。 However, it returns the following on the example above:但是,它在上面的示例中返回以下内容:

1622442800000000000000000000001

I suspect this has something to do with the limitations of the long datatype.我怀疑这与数据类型的限制有关。

How could I handle this problem?我该如何处理这个问题? Thanks!谢谢!

It's happening because in Python 3, / means "floating-point" division.这是因为在 Python 3 中, /表示“浮点”除法。 Try // instead.试试//代替。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在python中反复查找每个T数的数字总和的数字总和,直到成为单个数字? - how to find the sum of digits of sum of digits of each of T numbers repeatedly in python till it gets to being a single digit number? 通过在 Python 2.7 中递归添加数字,在程序中获得错误的总和以将数字压缩为单个数字 - Getting wrong sum in program to condense a number to a single digit by adding the digits recursively in Python 2.7 Python函数求和 - Python function to sum digits 如何生成一个 3 位数字的列表,它们的数字总和等于 17? - how to generate a list of 3-digit numbers the sum of their digits equal 17? 设计一个递归函数,使用digit_sum计算数字之和 - Designing a recursive function that uses digit_sum to calculate sum of digits 在 python 中查找数字的总和直到总和变为单个数字 - Finding sum of digits of a number until sum becomes single digit in python 编写一个函数getSumOfFirstDigit(numList),该函数接受一个正数列表,并返回列表中所有第一位数字的总和? - Write a function getSumOfFirstDigit(numList) that takes in a list of positive numbers and returns the sum of all the first digit in the list? 我如何优化这个递归 function 来计算其数字等于总和的 n 位十六进制数的数量? - How do I optimize this recursive function that counts the number of n-digit hexadecimal numbers whose digits equal a sum? 添加除某些数字/python之外的数字总和 - Add sum of numbers except certain digit / python Python字符串函数中的数字总和 - Python Sum of digits in a string function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM