floating-point - 浮点数的逻辑运算(使用 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)
解决方案
我可以解决 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;
}
推荐阅读
- java - 如何在显示更新的位置时避免谷歌地图路径方向与最后一个重叠?
- python - 如何权衡数据框中的列并将它们相加
- c - 如何将 C 中的两个整数数组与 for 循环合并
- ros - 如何阅读有组织的点云以保持图像分辨率与云的宽度和高度之间的对应关系?
- python - BERT - 从所有层中提取值
- reactjs - ReactJS,点击图片并打开链接
- html - Angular 简单 ngIf 倒置?
- c# - Asp .Net Core MVC 返回缓存数据请求
- vba - 将对话中的旧电子邮件移至子文件夹
- outlook - Outlook iOS App 显示发件人图标甚至按钮。如何?