Home > Software design >  C# Negative Number Result
C# Negative Number Result

Time:01-03

(First sorry for my bad English, I hope you understand me). I am trying to create 20 random number from 1-100 with declaring delegate and event, then check the 20 numbers if any number is bigger than 50 then multiply the numbers, if not sum all numbers.

using System;
using System.Linq;

namespace ConsoleApp
{
    class Program
    {
        // Delegate tanımla
        public delegate int MyDelegate(int[] arr);
        public event MyDelegate OnResultCalculated;

        static void Main(string[] args)
        {
            Program p = new Program();

            // 1-100 arasında 20 adet rastgele sayı üret
            Random rnd = new Random();
            int[] numbers = Enumerable.Range(1, 100).OrderBy(x => rnd.Next()).Take(20).ToArray();

            // Eğer 50'den büyük sayı varsa çarp, yoksa topla
            int result = numbers.Any(x => x > 50) ? p.Multiply(numbers) : p.Add(numbers);

            // Event'i tetikle
            p.OnResultCalculated?.Invoke(numbers);
            Console.WriteLine(result);
            Console.ReadLine();
        }

        public int Multiply(int[] arr)
        {
            return arr.Aggregate(1, (a, b) => a * b);
        }

        public int Add(int[] arr)
        {
            return arr.Sum();
        }
    }
}

The code works but sometimes I get a negative number result. What is the problem?

CodePudding user response:

Like the comments tell you, it is possible that int is not big enough for your result. The highest possible value is 100^20. But this is just theoretical. So your int is to small for such numbers. The max. possible value of int is 2.147.483.647. If you calculate this value 1, it will result in the smallest value of int: -2.147.483.648. This is the reason why you may have a negative value: If the value is higher than the max. value of int, it will start from the smallest again.

enter image description here

One possible way is to reduce the random value, like you did. If you change int to long, the possibility of running into this issue is smaller, but still there.

If you combine both it will be a possible solution. Change the result type to long and just use 5 values. 100^5 is smaller than long.MaxValue.

CodePudding user response:

I just reduced the created 20 numbers to 5 and it is work fine

  •  Tags:  
  • c#
  • Related