Search code examples
c#for-loopsharpdevelopabsolute-value

Why is this small C# program on SharpDevelop which uses 'for' loops not working?


I'm a complete beginner. I've written a small C# program on SharpDevelop. Here it is:

double i, j;

for(i=1; i<=30; i+=(1/60))
{
    for(j=1+1/60; j<=30; j+=(1/60))
    {
        if(Math.Abs(Math.Log(i)/Math.Log(j)-0.63092975357)<=0.00001)
        {
            Console.WriteLine("ln("+i+")   ln("+j+")");
        }
    }
}

        Console.ReadKey(true);

My program is supposed to find the i and the j for which ln(i)/ln(j)=0.63092975357 (for example) i and j are necessarily equal to n/60 and m/60 respectively, where n and m are positive integers. (I know I can use type int instead of type double, but I would like to make it work with the type double.)

But it doesn't work. When I click on "Run Project", the black screen pops up, but nothing happens... And SharpDevelop doesn't point out any errors...

So what mistakes did I make? And how to fix my program?


Solution

  • Integer division.

    1/60 = 0
    

    You need 1 / 60.0d instead.

    When you divide by an integer you will get an integer result. Integers are not capable of storing decimals.

    When you are doing 1/60 you expect 0.0166666666666667 but it is infact 0.

    This code now works

    double i, j;
    
    for(i=1; i<=30; i+=(1/60d))
    {
      for(j=1+1/60d; j<=30; j+=(1/60d))
      {
          if(Math.Abs(Math.Log(i)/Math.Log(j)-0.63092975357)<=0.00001) 
              Console.WriteLine("ln("+i+")   ln("+j+")"); 
      }
    }
    

    EDIT: *Probally worth mentioning, writing 60d ensures that 60 is a double type. Hence your division now retuns a double *