所有花车都是双打吗? [英] All floats are doubles?

查看:48
本文介绍了所有花车都是双打吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读教科书,上面写着:

I'm reading textbook that says this:

默认情况下,C ++将您在程序源代码中键入的所有浮点数(例如7.33和0.0975)都视为双精度值.

C++ treats all floating-point numbers you type in a program's source code (such as 7.33 and 0.0975) as double values by default.

我觉得这有点奇怪,而且从未听说过.看起来很浪费?如果不指定精度,为什么还要提高精度?为什么要使用两种不同的类型来表示相同的内容?那长双呢?

I find this a bit odd and have never heard of it. Seems wasteful? Why get extra precision if you don't specify it? Why have two different types that mean the same thing? What about a long double?

推荐答案

这是指浮点文字.

这与说您在代码中写入的任何整数始终被视为(带符号的) int 相同.将其分配给变量后,您将立即获得该变量的类型.

This is the same as saying that any integer number you write in code is always treated as a (signed) int. As soon as you assign this to a variable, you will get the type of the variable.

但是,在计算中使用独立文字时,您将获得用于该计算的文字类型,可能会触发隐式类型转换:

However, when using standalone literals in computation you will get the type of the literal for that computation, potentially triggering implicit type conversions:

float f = 3.141;    // f is of type float, even though the literal was double
auto d = f * 2.0;   // d will be of type double because of the literal 2.0
auto f2 = f * 2.0f; // f2 will be of type float again

第二行的计算涉及两种不同的类型:变量的类型 f float .即使它是从 double 文字构造的,但变量的类型才是最重要的.另一方面,文字的类型 2.0 double ,因此触发了隐式转换以进行计算.因此,实际的乘法是两个 double s

The computation on the second line involves two different types: The type of the variable f is float. Even though it was constructed from a double literal, the type of the variable is what counts. The type of the literal 2.0 on the other hand is double and hence triggers an implicit conversion for the computation. The actual multiplication is therefore performed as a multiplication of two doubles.

如果您希望独立值具有特定类型,请使用匹配的文字.

If you want a standalone value to have a specific type, use the matching literal.

这篇关于所有花车都是双打吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆