-5

I am starting to learn C# and here is a program that calculate percentage using System;

namespace CheckDegree
{
    class Program
    {
        static void Main(string[] args)
        {
            int totalmarks=0;
            for (int i = 0; i < 5;  i++ ) {
            Console.WriteLine("Please enter a subject.");
            string subject = Console.ReadLine();
            Console.WriteLine("Enter the mark for {0}",subject);
            int mark = Convert.ToInt32(Console.ReadLine());
            totalmarks = totalmarks + mark;
            }
            double percentage = (totalmarks / 500) * 100; 
            if (percentage >= 60)
            {
                Console.WriteLine("You got {0} and has been awarded a first division", percentage );
            }
            else if (percentage >= 50 && percentage <= 59)
            {
                Console.WriteLine("You got {0} and has been awarded a second division", percentage);
            } 
            else if (percentage < 40 )
            {
                Console.WriteLine("You got {0} and thus have failed!!!", percentage);
            }
            Console.ReadKey();
        }
    }
}

However percentage always output 0

double percentage = (totalmarks / 500) * 100;  
user2650277
  • 6,289
  • 17
  • 63
  • 132

1 Answers1

2

Instead of dividing by 500, divide by 500.0. It's treating it as an integer divided by an integer, which will be 0.#####. Since it's an integer, the decimal gets dropped. Then, 0 times 100 is still 0.

Changing 500 to 500.0 will force the division to be a double, which will preserve your decimal value.

Vahlkron
  • 464
  • 3
  • 15