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

  1. In the .NET Editor, locate the Console.WriteLine() statements that are used to display the course information.
  2. Remove the following code from the previous exercise:C#CopyConsole.WriteLine($"{totalGradePoints} {totalCreditHours}"); Since you’ve verified your values are correct, this line is no longer needed.
  3. Create a blank code line above the Console.WriteLine() statements.
  4. On the blank code line that you created, to initialize a variable that will store the final GPA, enter the following code:C#Copydecimal gradePointAverage = totalGradePoints/totalCreditHours;
  5. 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.
  6. To retrieve a decimal value from the division, update your code as follows:C#Copydecimal gradePointAverage = (decimal) totalGradePoints/totalCreditHours;
  7. Navigate to the last Console.WriteLine() statement and create a new blank code line after the last statement.
  8. To display the final GPA, enter the following code:C#CopyConsole.WriteLine($"Final GPA: {gradePointAverage}");
  9. To view the results, select Run.

affiliation

Leave a Reply

Your email address will not be published. Required fields are marked *