我很好奇为什么 float 文字必须这样声明:
float f = 0.1f;
代替
float f = 0.1;
为什么默认类型是double,为什么编译器不能从赋值左侧推断它是float?谷歌只解释默认值是什么,而不是为什么会这样。
最佳答案
Why is the default type a double?
这是最好向 Java 语言的设计者提出的问题。他们是唯一知道做出该语言设计决定的真正原因的人。但我希望推理大致如下:
他们需要区分这两种类型的文字,因为从数学的角度来看,它们实际上意味着不同的值。
假设他们将“float”设为文字的默认值,请考虑这个示例
// (Hypothetical "java" code ... )
double d = 0.1;
double d2 = 0.1d;
在上面,d 和 d2 实际上会有不同的值。在第一种情况下,低精度 float 值在分配点被转换为更高精度的 double 值。但是您无法恢复不存在的精度。
我假设这两个语句都是合法的,并且意味着不同的东西是一个坏主意......考虑到第一个语句的实际含义不同于“自然"的意思。
按照他们的方式去做:
double d = 0.1f;
double d2 = 0.1;
都是合法的,但又意味着不同的东西。但是在第一个语句中,程序员的意图是明确的,而第二个语句“自然”的含义是程序员得到的。在这种情况下:
float f = 0.1f;
float f2 = 0.1; // compilation error!
...编译器拾取不匹配。
I am guessing using floats is the exception and not the rule (using doubles instead) with modern hardware so at some point it would make sense to assume that the user intends 0.1f when he writes
float f = 0.1;
他们可以这样做了。但是问题在于提出了一组有效的类型转换规则......并且非常简单,以至于您不需要 Java 学学位即可真正理解。让 0.1 在不同的上下文中表示不同的东西会令人困惑。考虑一下:
void method(float f) { ... }
void method(double d) { ... }
// Which overload is called in the following?
this.method(1.0);
编程语言设计很棘手。一个领域的变化可能会对其他领域产生影响。
更新以解决@supercat 提出的一些问题。
@supercat: Given the above overloads, which method will be invoked for method(16777217)? Is that the best choice?
我错误地注释了...编译错误。事实上答案是method(float)。
JLS 是这样说的:
15.12.2.5. Choosing the Most Specific Method
If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses the rule that the most specific method is chosen.
...
[The symbols m1 and m2 denote methods that are applicable.]
[If] m2 is not generic, and m1 and m2 are applicable by strict or loose invocation, and where m1 has formal parameter types S1, ..., Sn and m2 has formal parameter types T1, ..., Tn, the type Si is more specific than Ti for argument ei for all i (1 ≤ i ≤ n, n = k).
...
The above conditions are the only circumstances under which one method may be more specific than another.
A type S is more specific than a type T for any expression if S <: T (§4.10).
在这种情况下,我们将比较适用于调用的 method(float) 和 method(double)。由于 float <:>double,它更具体,因此会选择method(float)。
@supercat: Such behavior may cause problems if e.g. an expression like
int2 = (int) Math.Round(int1 * 3.5)orlong2 = Math.Round(long1 * 3.5)gets replaced withint1 = (int) Math.Round(int2 * 3)orlong2 = Math.Round(long1 * 3)The change would look harmless, but the first two expressions are correct up to
613566756or2573485501354568and the latter two fail above5592405[the last being completely bogus above715827882].
如果你说的是一个做出改变的人......好吧。
但是,编译器不会在您背后进行更改。例如,int1 * 3.5 的类型为 double(int 被转换为 double),所以你结束向上调用 Math.Round(double).
作为一般规则,Java 算术将隐式从“较小”转换为“较大”数字类型,但不会从“较大”转换为“较小”。
但是,您仍然需要小心,因为(在您的舍入示例中):
整数和浮点的乘积可能无法以足够的精度表示,因为(比如说)float 的精度位比 int 少。
将 Math.round(double) 的结果转换为整数类型可以转换为整数类型的最小值/最大值。
但所有这些都表明,编程语言中的算术支持很棘手,对于新手或粗心的程序员来说,不可避免地会遇到一些问题。
关于java - 声明 float ,为什么默认类型为 double?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16369726/
类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc
我有一个模型:classItem项目有一个属性“商店”基于存储的值,我希望Item对象对特定方法具有不同的行为。Rails中是否有针对此的通用设计模式?如果方法中没有大的if-else语句,这是如何干净利落地完成的? 最佳答案 通常通过Single-TableInheritance. 关于ruby-on-rails-Rails-子类化模型的设计模式是什么?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.co
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我主要使用Ruby来执行此操作,但到目前为止我的攻击计划如下:使用gemsrdf、rdf-rdfa和rdf-microdata或mida来解析给定任何URI的数据。我认为最好映射到像schema.org这样的统一模式,例如使用这个yaml文件,它试图描述数据词汇表和opengraph到schema.org之间的转换:#SchemaXtoschema.orgconversion#data-vocabularyDV:name:namestreet-address:streetAddressregion:addressRegionlocality:addressLocalityphoto:i
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
这是在Ruby中设置默认值的常用方法:classQuietByDefaultdefinitialize(opts={})@verbose=opts[:verbose]endend这是一个容易落入的陷阱:classVerboseNoMatterWhatdefinitialize(opts={})@verbose=opts[:verbose]||trueendend正确的做法是:classVerboseByDefaultdefinitialize(opts={})@verbose=opts.include?(:verbose)?opts[:verbose]:trueendend编写Verb
我正在使用active_admin,我在Rails3应用程序的应用程序中有一个目录管理,其中包含模型和页面的声明。时不时地我也有一个类,当那个类有一个常量时,就像这样:classFooBAR="bar"end然后,我在每个必须在我的Rails应用程序中重新加载一些代码的请求中收到此警告:/Users/pupeno/helloworld/app/admin/billing.rb:12:warning:alreadyinitializedconstantBAR知道发生了什么以及如何避免这些警告吗? 最佳答案 在纯Ruby中:classA
它不等于主线程的binding,这个toplevel作用域是什么?此作用域与主线程中的binding有何不同?>ruby-e'putsTOPLEVEL_BINDING===binding'false 最佳答案 事实是,TOPLEVEL_BINDING始终引用Binding的预定义全局实例,而Kernel#binding创建的新实例>Binding每次封装当前执行上下文。在顶层,它们都包含相同的绑定(bind),但它们不是同一个对象,您无法使用==或===测试它们的绑定(bind)相等性。putsTOPLEVEL_BINDINGput
我可以得到Infinity和NaNn=9.0/0#=>Infinityn.class#=>Floatm=0/0.0#=>NaNm.class#=>Float但是当我想直接访问Infinity或NaN时:Infinity#=>uninitializedconstantInfinity(NameError)NaN#=>uninitializedconstantNaN(NameError)什么是Infinity和NaN?它们是对象、关键字还是其他东西? 最佳答案 您看到打印为Infinity和NaN的只是Float类的两个特殊实例的字符串
我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)