Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
What's wrong in my code? I want to create function which will call a random numbers and multiple that or divide(in the random order). When I start the app, total result of multiplication(or division) is sometimes correct, but sometimes just equal 0.
How should I solve the problem?

What I have tried:

   Random rand = new Random();
           int num1 = rand.Next(1,15);
           int num2 = rand.Next(1,15);
int RandOperation = rand.Next(1,100);
           if (RandOperation % 2 == 0)
           {
               if (num2 % num1 == 0 & num2 > num1)
               {
                   Display.Text = Convert.ToString(num2) + "/" + Convert.ToString(num1);
                   total = num2 / num1;
               }

               else
               {
                   if (num1 % num2 == 0 & num1 > num2)
                   {
                       Display.Text = Convert.ToString(num1) + "/" + Convert.ToString(num2);
                       total = num1 / num2;
                   }
               }
           }
           else
           {
               Display.Text = Convert.ToString(num1) + "*" + Convert.ToString(num2);
               total = num1 * num2;
           }
Posted
Updated 13-Apr-16 3:38am
Comments
ZurdoDev 13-Apr-16 9:32am    
Debug your code.

1 solution

Well...What happens if num1 is 11 and num2 is 14, and RandOperation is 74?
It passes this test:
C#
if (RandOperation % 2 == 0)

But it fails this test:
C#
if (num2 % num1 == 0 & num2 > num1)

And it fails this test:
C#
if (num1 % num2 == 0 & num1 > num2)

So...it doesn't do anything to total at all, and you get a zero.
Try it: use the debugger and follow the execution through - you'll see what I mean!

"Ok I will try, but maybe there is a simple way to generate what I want?"

Well...that's going to depend on exactly what you want! :laugh:
I'm not sure why you are using the remainder in the if conditions at all - the way I'd do it is a bit simpler:
C#
Random rand = new Random();
int num1 = rand.Next(1, 15);
int num2 = rand.Next(1, 15);
int RandOperation = rand.Next(0, 2);
if (RandOperation == 0)
    {
    if (num1 < num2)
        {
        int temp = num1;
        num1 = num2;
        num2 = temp;
        }
    Display.Text = string.Format("{0} / {1}", num1, num2);
    total = num1 / num2;
    }
else
    {
    Display.Text = string.Format("{0} * {1}", num1, num2);
    total = num1 * num2;
    }
 
Share this answer
 
v2
Comments
Member 12355239 13-Apr-16 9:53am    
Ok I will try, but maybe there is a simple way to generate what I want?
OriginalGriff 13-Apr-16 10:19am    
Answer updated
Member 12355239 13-Apr-16 10:30am    
Thanks, almost exactly what I need.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900