0

I'm new to C# and keep getting a divide by zero error with this function, I think its to do with how I'm passing my parameters but I'm not sure - any ideas?

    double sqrRoot(int value, int sigFig)
    {
        int x=sigFig*100;
        for (int i=0; i<sigFig; i++)
        {
            x=1/2*(x+(value/x));
        }
        return x;
    }
    //Example usage
    Console.WriteLine(sqrRoot(125348,6));

(Returns the following error message in Solo Learn IDE)

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero. at SoloLearn.Program.g__sqrRoot0_0(Int32 value, Int32 sigFig) at SoloLearn.Program.Main(String[] args)

Hugh Evans
  • 39
  • 1
  • 6
  • 5
    It has to do with how int/int returns an int and not a decimal. So 3/2 = 1, 1/2 = 0, etc – Igor Jun 19 '18 at 19:40
  • Thanks, do you know how I might fix that? Like I said I'm new, should I be using float instead? – Hugh Evans Jun 19 '18 at 19:42
  • 1
    This really depends on what kind of precision you want. Float, double and decimal all have their pros and cons.. – TaW Jun 19 '18 at 19:43
  • 1
    If `sigFig` is 0, you're always going to attempt to divide by 0 no matter what data type you use. – gunr2171 Jun 19 '18 at 19:44
  • Division by 0 is not defined in mathemathics. In case you wonder why, this video can explain it better then me: https://www.youtube.com/watch?v=BRRolKTlF6Q And the computer is not able to calculate what Math Science has not figured out. Aside from that, there is also an issue with the types. You are division in integer, then cast to a type with decimal places. Either pick double/float to being with and live with the issues inherent in them: https://www.youtube.com/watch?v=PZRI1IfStY0 Or accept that imprecision in dividing with Integers. Also you define "value" but never use it. – Christopher Jun 19 '18 at 19:44
  • I understand why div 0 is an issue. I'm not used to handling data-type the way C# does and I tried changing all the integers in my code to decimal and I get the same error, any ideas? – Hugh Evans Jun 19 '18 at 19:48
  • You have to look at every single math op that's happening and look at the types. If you have Int and Int, the output will be Int. So look at all the operations on that nested line: int / int * (int + (int / int)). So there are actually two places with the problem. The interior (int/int) will have a problem, as will the very first "1/2" - which is an int/int - which will result in a 0. You probably want to change x to a double, and change 1/2 to 0.5. – Kevin Jun 19 '18 at 19:56
  • That works, thank you so much Kevin! – Hugh Evans Jun 19 '18 at 20:25

0 Answers0