Problem with writing out contens of a generic list

aindrea

Member
Joined
Jun 5, 2018
Messages
23
Programming Experience
1-3
I have written a small console application - I want to read in some strings which I parse as doubles. After the user pushed "r", the first double I add to a generic List<Double> is printed out.


My question is the following one - even though I make a typecast, for example if I enter 2.2 as the first number - the result which will finally be printed out is 22 in spite of the fact that I make a typecast. What am I doing wrong?


C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Average
{




class Program
    {


        private static List<Double> al = new List<Double>();
        private static int counter = 1;




        static void Main(string[] args)
        {
            compute();
        }


        private static void compute()
        {
            Console.WriteLine("Enter numbers like this: 2.3");


            Console.WriteLine("If you want to have the result, enter \"r\".");


            string sum = Console.ReadLine();


            try
            {


                if (sum.Equals("r"))
                {
                    Console.WriteLine((double)al[0]);
                    Console.ReadLine();
                }
                else
                { 
                    double d = Double.Parse(sum);
                    al.Add(d);
                    counter++;
                    compute();
                }
            }
            catch(Exception e) {
                Console.WriteLine("Something went wrong.");
            }


        }
    }
}
 
I just tested your code and it worked for me. I entered 1.2 and then 5.7 and then r and it output 1.2.

Your code is rather dodgy in that you are recursively calling 'compute'. You should rather be prompting the user for input in a loop. Recursion is great when it makes sense but it doesn't make sense here.
 
The only reason I can think of that your code wouldn't work as expected is if the culture settings are such that the dot is a group separator rather than a decimal separator.
 
Back
Top Bottom