【问题标题】:Logical operation with float number (with C & python)浮点数的逻辑运算(使用 C 和 python)
【发布时间】:2021-05-19 05:24:21
【问题描述】:

我是 Python 新手,目前正在使用逻辑运算比较 Python 和 C 语言。

我的问题是

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

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 AND 0.800000 是 0.000000)

【问题讨论】:

  • Check Out This Previous Post, Explains it All 在 python 1.0 中,浮点数为真,0.0 为假
  • 您正在传递一个int,其中printf 需要一个double。我建议始终启用编译器警告(至少在 gcc/clang 上 -Wall):godbolt.org/z/df1EME
  • 注:0.7&&0.7==1 将评估为 0.7&&(0.7==1),其评估结果为 false(或 C 中的 0)。

标签: floating-point boolean decimal logical-operators operation


【解决方案1】:

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

对于理解 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中编写条件表达式时似乎很重要..)


关于第二季度,我可以在您的帮助下解决它:

将 %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;
  }

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    • 2011-06-25
    • 1970-01-01
    • 2014-09-16
    • 2015-08-31
    相关资源
    最近更新 更多