none
Math problem RRS feed

  • Question

  •                     xpercent = ((xincrease / xprogressBar.Maximum) * 100);

    In the code above xincrease is an int and equals 349, xprogressBar.Maximum equals 350. I would expect xpercent to equal 99.71, but it equals 0. I have tried declaring xpercent as an int, decimal, double and float, but each time xpercent equals 0.

    Can anyone tell me why?

    Thanks in advance.


    DrewT1755

    Tuesday, July 3, 2018 3:17 PM

Answers

All replies

  • You can do :

    double xpercent = ((double)xincrease / xprogressBar.Maximum) * 100;

    • Marked as answer by DrewT1755 Tuesday, July 3, 2018 3:42 PM
    Tuesday, July 3, 2018 3:30 PM
  • You need to think about what you're doing.  Think about doing 349/350 as an integer division.  The result is 0.

    When you're doing integer computer arithmetic where truncation and round-off errors are a problem, always do the multiplication first:

        xpercent = xincrease * 100 / xprogressBar.Maximum;

    Now you're doing 34900/350, which is 99.


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Tuesday, July 3, 2018 4:49 PM