Task 14 - Im getting the wrong result and I dont know why Help

Back to Problem Solutions forum

gadekryds.ds     2015-04-06 20:55:06

Expected Result: 1717 My result: 1383

Using my code with the test example works just fine, but when I try it with testdata i get the wrong result.

static double sum = 3771;
string[] testData = new string[] {"* 402", "* 689", "+ 5008", "* 8", "+ 5", "+ 4", "* 734", "+ 6718", "* 95", "* 8", "+ 630", "+ 5765", "* 5206", "+ 685", "+ 9916", "* 24", "+ 76", "+ 548", "+ 10", "+ 25", "* 91", "+ 7786", "* 754", "* 262", "* 19", "* 71", "+ 141", "* 659", "* 9", "+ 1914", "+ 64", "* 6030", "* 155", "* 8", "* 3", "* 59", "* 16", "+ 8", "+ 913", "* 7172", "+ 202", "* 10", "* 68", "* 76", "* 933", "* 2", "* 56", "+ 772", "+ 392", "+ 377", "+ 968", "+ 7", "* 459", "% 2159" };
        try
        {                
            for (int i = 0; i < testData.Length; i++)
            {

                if (testData[i].Contains('*'))
                {
                    double value = double.Parse(testData[i].Substring(2));
                    sum = sum * value;
                }
                else if (testData[i].Contains('+'))
                {
                    double value = double.Parse(testData[i].Substring(2));
                    sum = sum + value;
                }                   
                else if (testData[i].Contains('%'))
                {
                    double value = double.Parse(testData[i].Substring(2));
                    sum = sum % value;
                }                   
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
            Console.ReadKey();
        }
        results = sum.ToString();
        WriteToText();
Rodion (admin)     2015-04-07 10:08:16
User avatar

Hi!

Thanks for your message!

One of the possible causes of error could be using double type. With that many multiplications and additions you probably will get value longer than 14-15 digits and it is maximum which double can hold without losing precision.

Meanwhile intermediate results need not be so large. This exercise was created to show you idea that modulo could be applied after any of intermediate operations, as many times as you want.

gadekryds.ds     2015-04-07 10:20:08

Thank you, Admin!

The issue was as you said, the intermediate results got too large, repositioning the modulus gave the correct answer.

Please login and solve 5 problems to be able to post at forum