# DivideByZeroException

• ### Question

• The offset is going to zero, can someone tell me why and help me resolve this issue. I get a DivideByZeroException exception during the loop because the offset goes to zero

for (int offset = 0; offset <= File.Length; offset += buffersize)

{

I get a DivideByZeroException exception during the loop.

totalspeed = Math.Round((offset / (sw.ElapsedMilliseconds / 1000)) * 0.00000762939453125, 1);

}

pianoboyCoder

Tuesday, November 14, 2017 7:16 AM

### All replies

• Add "if (sw.ElapsedMilliseconds > 0)" to be line before the division?
Tuesday, November 14, 2017 7:32 AM
• Try replacing 1000 with 1000.0 too.

Tuesday, November 14, 2017 8:59 AM
• Hi pianoboyCoder,

In your code you are starting the value of "offset" from zero. So, when first loop iteration occurs it gets the offset value as zero and tries to perform division operation in the following line:

`totalspeed = Math.Round((offset / (sw.ElapsedMilliseconds / 1000)) * 0.00000762939453125, 1);`

You can start you loop from 1 and rewrite it like below:

```for (int offset = 1; offset <= File.Length; offset += buffersize)
{
}```

Thanks,
Sabah Shariq

[If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

Tuesday, November 14, 2017 9:26 AM
• try this

`totalspeed = Math.Round((offset / (sw.ElapsedMilliseconds / 1000.00)) * 0.00000762939453125, 1);`

giving error because (sw.ElapsedMilliseconds / 1000) is returning as 0 as both value are integer so it will return integer if  sw.ElapsedMilliseconds is less than 1000 expression will be evaluated as 0.

Ashish Pandey

Wednesday, November 15, 2017 10:57 AM
• Check what is numerator and denominator. Division By Zero is a condition where you try to do division but demoninator is zero.

Numerator being zero is okay because the result will be simply zero.

offset here is numerator.

Wednesday, November 15, 2017 11:22 PM
• Hi pianoboyCoder,

If your issue is solved please Mark as answer or Vote as helpful post to the appropriate answer so that it will help other members to find solution if they faces similar issue.

Your understanding and cooperation will be grateful.

Thanks,
Sabah Shariq

[If a post helps to resolve your issue, please click the "Mark as Answer" of that post or click "Vote as helpful" button of that post. By marking a post as Answered or Helpful, you help others find the answer faster. ]

Thursday, December 14, 2017 8:51 AM