简体   繁体   English

我应该用 0 或 0.0 初始化一个浮点 (double,float) 变量吗?

[英]Should I initialize a floating-point (double,float) variable with 0 or 0.0?

My question is: Should i initialize a floating-point variable like a double or float with 0 or rather 0.0 (if i want to initialize it with a value equivalent to 0 of course)?我的问题是:我应该用0或更确切地说0.0初始化一个浮点变量,如doublefloat (当然,如果我想用等于0的值初始化它)?

Like for example:例如:

double var = 0.0;

in comparison to:相比之下:

double var = 0;

Does it make a difference?这有什么不同吗?


Question is open for C and C++, as i work with both and did not want to make the same question twice. C 和 C++ 的问题是开放的,因为我同时使用这两种方法并且不想两次提出相同的问题。 If there is a significant difference between those two with regards to especially that case, please mention which language is in your focus.如果这两者之间在特别是这种情况下存在显着差异,请提及您关注哪种语言。

With the half eye on C++, the case of the constructor might become also an influence to the topic and of course initialization in general is a broader topic in C++, but i don´t know whether this is influencing the answer or not.由于对 C++ 的半分关注,构造函数的大小写也可能会影响该主题,当然初始化通常是 C++ 中的一个更广泛的主题,但我不知道这是否会影响答案。

Huge thanks.非常感谢。

As @NathanOliver comments, it doesn't make a difference in this case .正如@NathanOliver 评论的那样,在这种情况下没有区别。 But it's a good habit to always say what you mean:但总是说出你的意思是一个好习惯:

double var = 0.0;

Where this habit will pay off is places like std::accumulate :这种习惯会得到回报的地方是std::accumulate

std::vector<double> v{1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9, 9.0, 10.1};

double sum = std::accumulate(v.begin(), v.end(), 0);  // 0 here is wrong!

this isn't going to work as std::accumulate is declared as:这不会起作用,因为std::accumulate被声明为:

template< class InputIt, class T >
constexpr T accumulate( InputIt first, InputIt last, T init );

so the 0 causes T to be int !所以0导致Tint

A double you can just initialize like this:您可以像这样初始化双精度:

double test = 0.0;

However, a float you have to initialize like this if you want to do it 100% correct:但是,如果要 100% 正确,则必须像这样初始化浮点数:

float test = 0.0f;

The f means that the number that precedes it is a float. f表示它前面的数字是一个浮点数。 If you leave it out, the number is interpreted as a double and automatically casted back to a float because your variable is of type float.如果您省略它,该数字将被解释为双精度值并自动转换回浮点数,因为您的变量是浮点型。 Leaving the f out doesn't cause any real trouble but it introduces unnecessary overhead.不使用f不会造成任何真正的麻烦,但会引入不必要的开销。 I believe something similar happens when you initialize a double with just 0 instead of 0.0, but I am not sure about this part.我相信当您仅使用 0 而不是 0.0 初始化双精度值时,会发生类似的事情,但我不确定这部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM