Logic Problems

How come when i run this i get 62 but i am trying to get the average...The average is 15.4 but when i compile it i get 62...why is that can some one help

using System;

class Average

{

public static void Main()

{

int num1;

int num2;

int num3;

int num4;

int num5;

num1 = 10;

num2 = 12;

num3 = 15;

num4 = 22;

num5 = 18;

float average = num1 + num2 + num3 + num4 + num5 / 5;

Console.WriteLine("Average is {0}",average);

Console.WriteLine("Press Enter enter to continue");

Console.ReadLine();

}

}




Answer this question

Logic Problems

  • MilkMover

    You're performing an integer mul & div and assigning it to a decimal, which is probably not what you wanted.

    In your code, change the average computation line to:


    average = (double)sum / 5;
     


    That should give you the "precise" result that you're expecting.

    If you want to get input from users, this is probably one way to do it.


    public static void Main()
    {
        int sum = 0;
        for (int i = 0; i < 5; i++)
        {
            Console.Write("Enter the data #{0}: ", i + 1);
            string stringData = Console.ReadLine();

            int data;
            if (!int.TryParse(stringData, out data))
            {
                Console.WriteLine("Invalid input.  Aborting");
                return;
            }

            sum += data;
        }

        double average = (double)sum / 5;

        Console.WriteLine("Average is {0}", average);
        Console.ReadLine();
    }


     


  • Yorro

    Well i got it to give me the average but i am looking for it to give me the exact average like a claculator...i tried declaring as decimal types using the M literal but i get not change....here check it out to see if you can help....How do i add an input five number feature

    using System;

    class Average

    {

    public static void Main()

    {

    int num1;

    int num2;

    int num3;

    int num4;

    int num5;

    decimal average;

    num1 = 10;

    num2 = 33;

    num3 = 15;

    num4 = 22;

    num5 = 18;

    int sum = num1 + num2 + num3 + num4 + num5;

    average = sum / 5;

    Console.WriteLine("Average is {0}",average);

    Console.WriteLine("Press Enter enter to continue");

    Console.ReadLine();

    }

    }



  • Jay Kappel

    http://msdn.microsoft.com/library/default.asp url=/library/en-us/csref/html/vclrfInt_PG.asp


    ___________________________
    I think I deleted the Internet....

  • Logic Problems