Division

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • shapper

    Division

    Hello,

    I have the following:

    V = A / B * 100

    V, A and B are integers. How can I be sure that the result would be an
    integer.

    And how can I assign a value to V in case B=0 creating a division by
    0.

    Thanks,
    Miguel
  • Jon Skeet [C# MVP]

    #2
    Re: Division

    shapper <mdmoura@gmail. comwrote:
    I have the following:
    >
    V = A / B * 100
    >
    V, A and B are integers. How can I be sure that the result would be an
    integer.
    It always will be, because that's how division works in C#. If you mean
    you need to check that A really is divisible by B, use %:

    if ((A % B) != 0)
    {
    throw new ArgumentExcepti on(...);
    }
    And how can I assign a value to V in case B=0 creating a division by
    0.
    V = B == 0 ? WhateverValueYo uWant : A/B * 100;

    --
    Jon Skeet - <skeet@pobox.co m>
    Web site: http://www.pobox.com/~skeet
    Blog: http://www.msmvps.com/jon.skeet
    C# in Depth: http://csharpindepth.com

    Comment

    • qglyirnyfgfo@mailinator.com

      #3
      Re: Division

      How can I be sure that the result would be an integer.


      Are you concerned about overflow? is that the case, one option would
      be to use:
      int V = checked(A / B * 100);

      And how can I assign a value to V in case B=0 creating a division by.
      I have a feeling I am not understanding what you are asking and that
      the following is not the right answer but here is a best guess:

      int V;
      if(B == 0)
      {
      V = 0;
      }
      else
      {
      V = checked(A / B * 100);
      }

      Comment

      Working...