繁体   English   中英

Python 数学表达式求值

[英]Python mathematical expression evaluation

我试图解决一个随机问题,我使用了我建立的关系,当我在 python 中实现它时,它给我的结果与我计算的结果不同,所以我试图改变。

问题是我不明白 python 如何看到每个?!?

  • 这两个表达式有时会给出不同的结果:

在此处输入图像描述

  • 这是一个例子:
rows, columns = 4, 4

for row in range(2, rows+1):
    for column in range(1, columns+1):
        print('*'*15)
        result = ((column+1)//2) * ((row+1)//2)
        f_result = (column+1)//2 * (row+1)//2

        print('>> normal expression:', (column+1)//2, (row+1)//2)
        print('>> second expression:', ((column+1)//2), ((row+1)//2))
        print('>>               row:', row)
        print('>>            column:', column)
        print('>>           Results:', result, f_result)
    print()

  • 结果:

在此处输入图像描述

您需要先了解运算符优先级查看此链接

对于表达式

((col+1)//2) * ((row+1)//2) = (col+1)//2 * (row+1)//2

((col+1)//2) * ((row+1)//2) = ((4+1)//2) * ((4+1)//2)
                            = (5//2)*(5//2)
                            = 2 * 2
                            = 4
(col+1)//2 * (row+1)//2 = (4+1)//2 * (4+1)//2
                        = 5//2 * 5//2
                        = 2 * 5//2
                        = 10//2 (as * has higher precedence than //)
                        = 5

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM