Calculating percent done for progress dialog

2019-02-25 19:23发布

I am trying to use a progress dialog to show how long until 2 time intensive functions are done.

in my first function I have the total number to db entries and a counter for how many times i have gone through a do/while loop. when that gets done the progress dialog should be at 50%

so I do:

double total = (counter/dbEntries)*100; //counter and dbEntries are both int's

then I divide total by 2 because I want half the amount done because there are 2 functions

double realPercentDone = total/2.0;

so say counter is 3 and dbEntries is 36 that would equal 0.08 or 8% when multiplied by 100 but total is always 0. What am I doing wrong?

3条回答
Bombasti
2楼-- · 2019-02-25 20:09

If counter and dbEntries are both integers then it is likely performing integer division in the parenthesis of your first expression. 3 div 36 = 0.

Try changing it to something like this:

double total = 100.0 * counter / dbEntries;

or

double total = (1.0 * counter / dbEntries) * 100.0;

Note: use 100.0 and not 100 so as floating point calculations are done.

查看更多
姐就是有狂的资本
3楼-- · 2019-02-25 20:13

You should either cast, or use the double type for counter and entries. I assume you're using ints currently, and as ints go, 3/36=0, and of course 0*100 is still 0.

查看更多
beautiful°
4楼-- · 2019-02-25 20:14

Also, note that if you always divide total by 2, then you will never get to 100%, you will range between 0% and 50%.

查看更多
登录 后发表回答