c# - simple calculation not working for some reason -
alright, i'm trying calculate percentage of 2 values. should simple weird reason it's not working. i'm tired/dumb figure out. here's code, keeps returning 0, checked values while debugging , filescompleted being 295 , totalfilescount being 25002 returnvalue var 0, should 1 already.
private int calculatepercentcomplete(int filescompleted, int totalfilescount) { int returnvalue = (filescompleted / totalfilescount) * 100; if (returnvalue > 100 || returnvalue < 1) return 1; else return returnvalue; }
i checked values while debugging , filescompleted being 295 , totalfilescount being 25002 returnvalue var 0, should 1 already.
no, because arithmetic being done integers. first expression evaluated:
(filescompleted / totalfilescount)
that's 295 / 25002. result of integer arithmetic 0... , when multiply 100, you've still got 0. simplest fix multiplication first:
int returnvalue = (filescompleted * 100) / totalfilescount;
note that overflow if filescompleted
greater int.maxvalue / 100
. fix either doing in floating point arithmetic:
int returnvalue = (int)((filescompleted * 100.0) / totalfilescount);
... or using long
integer arithmetic:
int returnvalue = (int)((filescompleted * 100l) / totalfilescount);
neither of these necessary if don't expect have insane number of files, of course. (you're fine 42 million files...)
as side note, parameter names violate .net naming conventions. should camelcased - totalfilescount
, filescompleted
.
Comments
Post a Comment