Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

making double variables lower than 1

in my ASP.NET project i did a survey page that uses Application to save the votes. I have a problem with the making of the percentages amount. I've tried many things. here is the problematic part of my code:

    double x = (count / sum) ;
    double f = (count1 / sum) ;
    double g = (count2 / sum) ;
    double h = (count3 / sum) ;
    if (sum > 0)
    {
        a = (int)x * 100;
        b = (int)f * 100;
        c = (int)g * 100;
        d = (int)h * 100;
    }

I used breakpoints and figured out that the problem was in the double variables: the (count/sum) equals 0 anyway.

like image 557
user3519124 Avatar asked Mar 24 '26 05:03

user3519124


2 Answers

I'm assuming count and sum are integer types.

The result of division of 2 integers is a truncated integer.

You need to cast one side of the division to a double, then the result will be double

So

((double)count)/sum
like image 159
spender Avatar answered Mar 26 '26 20:03

spender


What are the datatypes of count, count[1-3] and sum? If they are integral types, then integer division is performed. This

int    x = 100   ;
int    y = 300   ;
double z = x / y ;

yields the value 0.0 for z.

Try something like

double h = (double) ( count3 / sum ) ;

You might also want to move your test for sum > 0 up: as coded, if sum is zero, you'll throw a DivideByZeroException before you get to your test, thus rendering your test moot.

like image 37
Nicholas Carey Avatar answered Mar 26 '26 18:03

Nicholas Carey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!