Skip to content

Char and int help

owain harris

Asked Aug 20, 2009, 4:02 AM EDT2 answers
Share
LinkedInX
Can any one help me? I am new to programming..
I am creating a console output to let a user enter a series of random numbers. The letters 'n' or 'N' will break the loop, and display the sum and average.

I can do most of this, execpt the only part confusing me is converting the char to an int, as entering a 'n' or 'N', will break it, as it is an int.

here is my code so far:

 class MyClass
    {
        static void Main(string[] args)
        {
            int num = 0;
            int i = - 1;
            int sum = 0;
            int avg = 0;



            do
            {
              Console.WriteLine("Enter N to quit");
                num = char.Parse(Console.ReadLine());
                i++;

                if (num == 'n')
                {
                    break;
                }
                else
                {
                    sum = sum + num;
                }
           
            } while (num != 'n' || num != 'N');

          
           avg = sum / i;

            Console.WriteLine("\nThe amount of numbers entered was: " + i);
            Console.WriteLine("\nSum is " + sum);
            Console.WriteLine("\naverage is " + avg);
            Console.WriteLine("\nProgram Finsihed");
            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
Code
Code

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Niradhip Chakraborty
    0
    If you try to convert a char to int then nothing but you are converting it into ascii.
    you can do it following way.
    string strInput = "N";
    int charValue = Convert.ToInt32(strInput);
    0
  • 0
    Best way to get Ascii value for any Keyboard character mean.,
    int ascii=Convert.ToInt16('N');
    do like this
    int ascii = Convert.ToInt16(e.KeyChar);
    if (ascii == 78 || ascii == 110)
    {
    break;
    }
    else
    {
    // do you work here
    }

    Surely this ll help you friend.
    0