Exercise – Format the decimal output
In this exercise, you’ll calculate the final GPA and modify the console output to achieve the desired reporting format. The GPA is equal to the sum of the total grade points divided by the sum of the total credit hours.
Calculate the final GPA
- In the .NET Editor, locate the Console.WriteLine() statements that are used to display the course information.
- Remove the following code from the previous exercise:C#Copy
Console.WriteLine($"{totalGradePoints} {totalCreditHours}");
Since you’ve verified your values are correct, this line is no longer needed. - Create a blank code line above the Console.WriteLine() statements.
- On the blank code line that you created, to initialize a variable that will store the final GPA, enter the following code:C#Copy
decimal gradePointAverage = totalGradePoints/totalCreditHours;
- Take a moment to consider the data types you’re dividing.When you want the result of a division calculation to be a decimal value, either the dividend or divisor must be of type decimal (or both). When you use integer variables in the calculation, you need to use the cast operator to temporarily convert an integer to a decimal.
- To retrieve a decimal value from the division, update your code as follows:C#Copy
decimal gradePointAverage = (decimal) totalGradePoints/totalCreditHours;
- Navigate to the last Console.WriteLine() statement and create a new blank code line after the last statement.
- To display the final GPA, enter the following code:C#Copy
Console.WriteLine($"Final GPA: {gradePointAverage}");
- To view the results, select Run.