整数除法浮点结果 [英] integer division to float result

查看:154
本文介绍了整数除法浮点结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 浮点ws;浮点ws;浮点ws;浮点ws;浮点ws; 
int i = Client.getInstance()。getUser()。getGespielteSpiele()-Client.getInstance()。getUser()。getGewonneneSpiele();
int zahl1 = Client.getInstance()。getUser()。getGewonneneSpiele();

ws = new Float((zahl1 / i));

我使用调试器检查值

  i = 64 

zahl1 = 22

ws = 0.0

为什么 ws 0.0的结果?我应该做什么才能获得正确的浮点数?

解决方案

当您将两个 int s你执行整数除法,在这种情况下将导致22/64 = 0。只有这样做完成后,你创建一个浮动。并且 0 浮动表示为 0.0 。如果你想执行浮点除法,你应该在之前划分:

  ws =( float)zahl1)/ i; 


I have to divide two integers and get a float as result My Code:

Float ws;
int i = Client.getInstance().getUser().getGespielteSpiele() -Client.getInstance().getUser().getGewonneneSpiele();
int zahl1 = Client.getInstance().getUser().getGewonneneSpiele();

ws = new Float((zahl1 / i));

I check the values with the debugger

i = 64

zahl1 = 22

ws = 0.0

Why is the result of ws 0.0? What I should do to get the correct float?

解决方案

When you divide two ints you perform integer division, which, in this case will result in 22/64 = 0. Only once this is done are you creating a float. And the float representation of 0 is 0.0. If you want to perform floating point division, you should cast before dividing:

ws = ((float) zahl1) / i;

这篇关于整数除法浮点结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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