当声明一个类型为float的变量时,是否有必要在值的末尾写上f?例如,float amount = .01和float amount = 0.01f,这里的f是什么意思,它有什么区别?还有,这里的#include库文件的作用是什么。
发布于 2018-07-13 17:39:56
这不是必需的:编译器将为您进行适当的数值转换。
0.01f是float类型的文本,而0.01是double类型。
有时,您需要显式识别,尤其是在使用模板或重载函数时:
void foo(const float&){
// Pay me a bonus
}
void foo(const double&){
// Reformat my disk
}
int main(){
foo(1.f);
}最后,如果您打算在double上使用float,那么一定要通读以下内容:Is using double faster than float?
发布于 2018-07-13 17:39:57
这取决于你如何定义你的变量。在定义中指定类型float时,不需要添加尾随f:
float amount = 0.1; /* This is fine, compiler knows the type of amount. */在这里添加多余的文字(float amount = 0.1f;)甚至可能被认为是不好的做法,因为您重复了类型信息,导致在更改类型时进行更多的编辑。
但在类型演绎的上下文中,您必须提供f字面量:
auto amount = 0.1f; /* Without the literal, compiler deduces double. */还有更微妙的上下文,其中类型演绎发生,例如
std::vector<float> vecOfFloats;
/* ... */
std::accumulate(vecOfFloats.cbegin(), vecOfFloats.cend(), 0.1f);这里,第三个参数用于推断std::accumulate操作的类型。如果你只是像std::accumulate(..., 0.1);一样调用它,那么vecOfFloats中的每个元素都会发生双精度到浮点的转换。
发布于 2018-07-13 17:40:49
.01是一个double文本。在初始化过程中存在到float的隐式转换
float amount = .01;.01f是一个float文本。初始化过程中没有转换
float amount = .01f;https://stackoverflow.com/questions/51322144
复制相似问题