Megakko
Megakko

Reputation: 3

C# Negative Number Result

I am trying to create randomly 20 numbers between 1 and 100. I want to achieve this with declaring a delegate and event. I check if any of the 20 numbers is bigger than 50, then I multiply the nubmers, 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 is working but sometimes I get a negative result. What is the problem?

Upvotes: 0

Views: 99

Answers (1)

Presi
Presi

Reputation: 827

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.

Upvotes: 1

Related Questions