首页 > 解决方案 > 浮点数的逻辑运算(使用 C 和 python)

问题描述

我是一名 Python 新手,目前正在使用逻辑运算将 Python 与 C 语言进行比较。

我的问题是

(我可以解决 Q1(C 中的逻辑运算),谢谢您的意见!)

Q1:C 中的逻辑运算

为什么 0.7 && 0.7 在 c 代码中不是 1?我希望它是“真实的”,因为

(bool)0.7 is 1 and (bool)0.8 is 1 // This is what I meant, revised after checking the comments, Thank you!

因为 0.7 和 0.8 是非零值。

Q2:Python中的逻辑运算

为什么 0.7 和 0.7 没有在 Python 的布尔类型中计算出来?这是因为动态规划吗?

请告诉我好吗?

先感谢您。


详细来说,来自python和c代码:

我期望

0.7&&0.7# 等于 1

. 同样地,

0.8&&0.8# 等于 1

但我从两个编译器得到的是:

来自 Python

 0.7 and 0.7
 Out[46]: 0.7

 0.8 and 0.8
 Out[47]: 0.8

来自 C 的代码如下:

 int main()
 {
     double a = 0.8;
     double b = 0.8;
     printf("%f AND %f is %f", a, b, a&&b);

     return 0;
  }

输出是:0.800000 AND 0.800000 是 0.000000

并且 a=0.7, b=0.7 结果是一样的。(0.800000 和 0.800000 是 0.000000)

标签: floating-pointbooleandecimallogical-operatorsoperation

解决方案


我可以解决 Q1(C 中的逻辑运算),谢谢您的评论!

有什么建议可以理解 Python 中将“0.7 和 0.7”计算为 0.7 而不是 1(或 True)的逻辑操作?

Python:

 0.7 and 0.7
 Out[46]: 0.7

不是

 0.7 and 0.7
 Out[46]: 1 #or true

(在 Python 中编写条件表达式时似乎很重要..)


关于 Q2,我可以在您的帮助下解决它:

将 %f 更改为 %d 后,我可以从 0.7&&0.7 得到 1(真),这是我所期望的。

 int main()
 {
     double a = 0.8;
     double b = 0.8;
     printf("%f AND %f is %d", a, b, a&&b);

     return 0;
  }

推荐阅读