在Java中浮点数除法中出现严重数字损坏?

huangapple go评论66阅读模式
英文:

Heavy number corruption in floating point division in Java?

问题

我一直在尝试使用Java浮点数除法来做一些简单的事情,已经阅读了几篇关于在值上进行一些最小更改的文章,但与我下面遇到的情况完全不同。

这是期望的代码:

float f = 1789773f / 1000000f;
System.out.printf("\n%.2f", f);
// 输出结果: 1.79

这是在使用变量时发生的情况:

int CLOCK = 1789773;
System.out.printf("\n%.2f", (float)CLOCK / (10^6));
// 输出结果: 13410.48

发生了什么?我不得不使用字面量'1000000f'而不是10^6才能使其正常工作。另外,我认为将除法元素之一转换为(float)会将所有内容都设置为浮点数,我不会最终执行整数运算。

英文:

I have been trying to do something simple with java floating point division, have read several articles on some minimal changes on values but nothing like I am having below.

This is the expected:

float f = 1789773f / 1000000f;
System.out.printf("\n%.2f", f);

Outputs: 1,79

This is what happens when I work with variables:

int CLOCK=1789773;
System.out.printf("\n%.2f", (float)CLOCK/(10^6));

Outputs: 13410,48

What is going on? I had to use the literal '1000000f' instead of 10^6 to make it work. Also, I thought that casting the one of the division elements with (float) would set everything as float and I would not end doing integer math.

答案1

得分: 3

10^6 不是一百万。它是12,因为 ^ 是按位异或运算符,而不是指数运算。

使用 1e6f,或者只使用 1000000f

英文:

10^6 is not a million. It's 12, because ^ is the bitwise xor operator rather than exponentiation.

Use 1e6f, or just 1000000f.

答案2

得分: 1

尝试使用这个代替:

int CLOCK = 1789773;
float fclock = (float) (CLOCK / (Math.pow(10, 6)));
System.out.printf("\n%.2f", fclock);
英文:

Try using this instead :

int CLOCK = 1789773;
float fclock = (float) (CLOCK/(Math.pow(10,6)));
System.out.printf("\n%.2f", fclock);

答案3

得分: 0

float CLOCK = 1789773f;
System.out.printf("\n%.2f", CLOCK / Math.pow(10, 6));

**OR**

int CLOCK = 1789773;
System.out.printf("\n%.2f", (float) (CLOCK / Math.pow(10, 6)));

尝试使用Math.pow(10, 6),这对我来说运行正常。
英文:
float CLOCK=1789773f;
System.out.printf("\n%.2f", CLOCK/Math.pow(10,6));

OR

int CLOCK=1789773;
System.out.printf("\n%.2f",(float) (CLOCK/Math.pow(10,6)));

Try to use Math.pow(10,6), it's working fine for me.

huangapple
  • 本文由 发表于 2020年8月22日 03:27:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63529013.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定