Search code examples
c#consoleconsole.writeline

I can't take marks for other subjects except for maths in C#


I have a c# code below. This code takes the name, marks for maths, computer, science, environment and History from the user and prints the total and percentage. The problem with this code is that it takes only the marks from maths. And it prints the output. But it takes the number from maths and assigns that number to all other subjects. Please help me out with this problem. The code goes like this:

using System;

 namespace test
 {
class Program
{
    public static void Main(string[] args)
    {
        int total = 500;
        Console.WriteLine("Hello This is my first C# Program. Hope you like it");
        Console.Write("Enter a name: ");
        String name = Console.ReadLine();
        Console.WriteLine($"Hello {name}");
        Console.Write("Enter the marks for Maths: ");
        int mathsMarks = Console.Read();
        Console.Write("Enter the marks for Science: ");
        int scienceMarks = Console.Read();
        Console.Write("Enter the marks for Computer: ");
        int computerMarks = Console.Read();
        Console.Write("Enter the marks for Environment: ");
        int environmentMarks = Console.Read();
        Console.Write("Enter the marks for Social: ");
        int socialMarks = Console.Read();
        int totalMarks = mathsMarks + scienceMarks + computerMarks + environmentMarks + socialMarks;
        Console.WriteLine($"The total marks is {totalMarks}");
        Console.WriteLine($"The percentage is %{(totalMarks/total)*100}");
    }

}
  }

Solution

  • You can see the difference is between how you read the name and how you read the score for the exams. The console.read does not return the int that you expect..it reads 1 char at a time until you press the Enter key.

    So change how you read the inputs from the user - maybe use console.ReadLine(). This will return data as a string and then you can explore the use of int.TryParse() to safely convert it to int.

    Also your final division will likely always return 0 as the division between integers will ignore the fraction ...so look up double and float types as well.