比较两个double或两个float值的最有效方法是什么?
简单地这样做是不正确的:
bool CompareDoubles1 (double A, double B)
{
return A == B;
}
Run Code Online (Sandbox Code Playgroud)
但是像这样:
bool CompareDoubles2 (double A, double B)
{
diff = A - B;
return (diff < EPSILON) && (-diff < EPSILON);
}
Run Code Online (Sandbox Code Playgroud)
似乎浪费处理.
有谁知道更聪明的浮动比较器?
我的价格是int6位数.我希望将它显示为String带有小数点(.)的结尾处的2位数int.我想使用a float但建议String用于更好的显示输出(而不是1234.5将1234.50).因此,我需要一个函数,它将采用intas参数并返回正确格式化String的结尾,小数点为2位数.
说:
int j= 123456
Integer.toString(j);
//processing...
//output : 1234.56
Run Code Online (Sandbox Code Playgroud) public class doublePrecision {
public static void main(String[] args) {
double total = 0;
total += 5.6;
total += 5.8;
System.out.println(total);
}
}
Run Code Online (Sandbox Code Playgroud)
上面的代码打印:
11.399999999999
Run Code Online (Sandbox Code Playgroud)
我怎么才能打印(或能够用它)11.4?
为什么下面的代码抛出了java数字格式异常?
BigDecimal d = new BigDecimal("10934,375");
Run Code Online (Sandbox Code Playgroud) 当我将1.265乘以10000时,使用Javascript时得到126499.99999999999.
为什么会这样?
我遇到了问题,无法解决问题.需要大师的帮助.以下是示例代码: -
float f=0.01f;
printf("%f",f);
Run Code Online (Sandbox Code Playgroud)
如果我们在调试期间检查变量中的值,则f包含'0.0099999998'值,printf的输出为0.010000.
一个.有没有办法可以强制编译器为float类型的变量赋值?
湾 我想将float转换为字符串/字符数组.怎么可能只将完全相同的值转换为字符串/字符数组.我想确保没有填充零,没有填充不需要的值,数字没有变化,如上例所示.
为什么ceil()会在没有分数部分的情况下进行均匀浮动?
当我尝试这样做时:
double x = 2.22;
x *= 100; //which becomes 222.00...
printf("%lf", ceil(x)); //prints 223.00... (?)
Run Code Online (Sandbox Code Playgroud)
但是当我将2.22的值更改为2.21时
x *= 100; //which becomes 221.00...
printf("%lf", ceil(x)); //prints 221.00... as expected
Run Code Online (Sandbox Code Playgroud)
我尝试用另一种方式使用modf()并遇到另一个奇怪的事情:
double x = 2.22 * 100;
double num, fraction;
fraction = modf(x, &num);
if(fraction > 0)
num += 1; //goes inside here even when fraction is 0.00...
Run Code Online (Sandbox Code Playgroud)
那么会发生什么是0.000 ...大于0?
谁能解释为什么这两种情况都会发生?此外,我正在使用RedHat中的cc版本4.1.2进行编译.
x = 4.2 - 0.1
Run Code Online (Sandbox Code Playgroud)
vb.net给出了4.1000000000000005
python给出的4.1000000000000005
Excel给出了4.1
calc calc给出4.1
这种情况发生的原因是什么?
如果我有以下代码(这是用.NET编写的)
double i = 0.1 + 0.1 + 0.1;
Run Code Online (Sandbox Code Playgroud)
为什么不i相等0.3?
有任何想法吗?
在Flash中创建一个新的AS3文档,粘贴以下代码并运行它:
var a:Number=0;
trace(a) // 0
a+=0.3;
trace(a) // 0.3
a+=0.3;
trace(a) // 0.6
a+=0.3;
trace(a) // 0.8999999999999999
a+=0.3;
trace(a) // 1.2
a+=0.3;
trace(a) // 1.5
a+=0.3;
trace(a) // 1.8
a+=0.3;
trace(a) // 2.1
a+=0.3;
// ^ This is the output. Notice the inaccuracy starting from 0.9 / 0.89
Run Code Online (Sandbox Code Playgroud)
为什么错误?我只是做一个普通的高分辨率加法.
任何解决方法?