user3519124
user3519124

Reputation: 69

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.

Upvotes: 2

Views: 79

Answers (3)

Nicholas Carey
Nicholas Carey

Reputation: 74365

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.

Upvotes: 3

spender
spender

Reputation: 120518

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

Upvotes: 7

zmbq
zmbq

Reputation: 39059

Your count and sum variables are probably integers. Cast one of them to double:

double x = count / (double)sum;

UPDATE:

Actually, if you want the percentage as an integer, you can skip the doubles altogether:

int a = 100 * count / sum;

Upvotes: 1

Related Questions