C++ c+中的相同算法+;和python,但输出不同

C++ c+中的相同算法+;和python,但输出不同,c++,python,C++,Python,C++ #包括 #包括 #包括 使用名称空间std; 无符号长整型t,n,i,m,su,s,k; int main() { cin>>n; 如果(n==0) { cout这与Python3与Python2的对比有关 在Python 2中,如果分子和分母都是整数,则/是整数地板除法: import math n = int(input()) if n==0: print('0') else: m = int(math.sqrt(n)) su = int(m*(m+1)/2)

C++

#包括
#包括
#包括
使用名称空间std;
无符号长整型t,n,i,m,su,s,k;
int main()
{
cin>>n;
如果(n==0)
{
cout这与Python3与Python2的对比有关

在Python 2中,如果分子和分母都是整数,则
/
是整数地板除法:

import math
n = int(input())
if n==0:
    print('0')
else:
    m = int(math.sqrt(n))
    su = int(m*(m+1)/2)
    s = n-1
    i=2
    while i*i<=n:
        k = int(n/i)
        s = s + ((k-1)*i) + int(k*(k+1)/2) - su
        i = i+1
    print(s)
Python 3.3.2 (default, May 21 2013, 11:50:47) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/3
0.6666666666666666
>>> 2//3
0
>>> 1/2 == 1.0/2.0
True
>>> 1//2 == 1.0/2.0
False
请注意,在Python2中,如果分子或分母都是浮点数,则结果将是浮点数

但是Python 3将
/
更改为“真正的除法”,您需要使用
/
来获得整数地板除法:

Python 2.7.1 (r271:86882M, Nov 30 2010, 10:35:34) 
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/3
0
>>> 2.0/3.0
0.6666666666666666
>>> 
>>> 1/2 == 1.0 / 2.0
False
C++在整数之间使用下限除法:

import math
n = int(input())
if n==0:
    print('0')
else:
    m = int(math.sqrt(n))
    su = int(m*(m+1)/2)
    s = n-1
    i=2
    while i*i<=n:
        k = int(n/i)
        s = s + ((k-1)*i) + int(k*(k+1)/2) - su
        i = i+1
    print(s)
Python 3.3.2 (default, May 21 2013, 11:50:47) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/3
0.6666666666666666
>>> 2//3
0
>>> 1/2 == 1.0/2.0
True
>>> 1//2 == 1.0/2.0
False
在Python 2中,我得到:

322467033612360629
如果更改此行:

s=s+((k-1)*i)+int(k*(k+1)/2)-su

s=s+((k-1)*i)+int(k*(k+1)//2)-su#注意“//”


< P> >它将在Python 3 < /p>下解决这个问题:我问N是否被输入1000000000作为输入感谢人,它解决了我的问题。请解释一下这个修复是如何使用Python的版本的?当我用Python 2.7运行Python代码时,我得到了<代码> 322467033612360628 < /Cord>,它与C++的输出相匹配。Python 2.7.3和Python 3.2.3给出了不同的答案。版本是Python 3.2.3此表达式:
s=125000001750008744+((333333-1)*3)+int(333333*(333+1)/2)-499991253
在python2和python3中产生不同的结果。编辑:删除了变量t,因为它会造成混淆-这是始终提供最简单的程序来重新创建问题的一个很好的理由。请参阅。
322467033612360629
322467033612360628