Division

S

shapper

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
 
J

Jon Skeet [C# MVP]

shapper said:
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 ArgumentException(...);
}
And how can I assign a value to V in case B=0 creating a division by
0.

V = B == 0 ? WhateverValueYouWant : A/B * 100;
 
Q

qglyirnyfgfo

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);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads

Double Division 10
Double NAN to 0 1
ref parameter 12
Number Extension 4
Interface Rewrite? 6
How to create a macro to replace one line with a few new lines? 2
Find Ints in List ... 4
Prevent cursor/focus from moving 2

Top