gpt4 book ai didi

c++ - 使用int错误计算float变量

转载 作者:行者123 更新时间:2023-11-28 05:45:43 24 4
gpt4 key购买 nike

我运行以下代码:

// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int x=4,y=2,z=11;
float p;
p=7+z/y-x*2;
cout<<p;
return 0;
}

x, y, z 声明为整数。为什么 p 得到一个 int 而 p 被声明为 float?

谢谢。

最佳答案

如果 a 和 b 是整数,那么 a/b 的结果将始终是整数,而不是 float 。除法结果只是截断为整数值,浮点部分被丢弃。

在表达式 7+z/y-x*2 中只使用整数变量,这就是结果也是整数的原因。

作为一个选项,您可以将右侧的操作数之一转换为 float ,然后整个表达式将被威胁为 float :

7+z/(float)y-x*2

关于c++ - 使用int错误计算float变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36257415/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com