简体   繁体   English

基本java计算问题

[英]Basic java calculation issue

 Cursor ca2 = dbh1.getReadableDatabase().query(DatabaseHelper.TABLE_NAME, null, null,     null, null, null, null);
 int countTotal = ca2.getCount();
 Cursor ca1 = dbh1.getReadableDatabase().query(DatabaseHelper.TABLE_NAME, null, DatabaseHelper.VALUE6 + "='Automatic'", null, null, null, null);
 int count = ca1.getCount();

 int percentTrans = ((count/countTotal)*100);
 statText=(EditText)findViewById(R.id.etext3);
 statText.setText(Integer.toString(percentTrans));

 Toast toast=Toast.makeText(this, Integer.toString(percentTrans), 2000);
 toast.show();

Hello, i have a silly problem here.你好,我这里有一个愚蠢的问题。 I want to the percentage by dividing count over countTotal and multiplying that by 100. percentTrans is integer by nature and this value will be passed to an edit text which requires that percentTrans be converted to string.我想通过将 count 除以 countTotal 并将其乘以 100 来计算百分比。percentTrans 本质上是 integer,此值将传递给需要将 percentTrans 转换为字符串的编辑文本。 count is 2 and countTotal is 3. But i get 0 as the result. count 是 2,countTotal 是 3。但结果是 0。 Any ideas?有任何想法吗?

count/countTotal is int too and (int)(2/3) is 0 . count/countTotal也是int并且(int)(2/3)0

write it as (count*100/countTotal)写成(count*100/countTotal)

Integer math is not like using a calculator - do this instead: Integer 数学不像使用计算器 - 而是这样做:

int percentTrans = Math.round(count * 100.0f / countTotal);

this does all of the calculations as floating point numbers (it does this implicitly when you specify your 100.0f to be a float) and then rounds it to the appropriate integer value at the end这会将所有计算作为浮点数进行(当您将 100.0f 指定为浮点数时,它会隐式执行此操作),然后在最后将其四舍五入为适当的 integer 值

jus do calculation as upper shown answer and put value in edit text as followin:只需按照上面显示的答案进行计算,并将值放入编辑文本中,如下所示:

statText.setText(String.valueOf(percentTrans));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM