Algorithm: Best way to create solve this algorithm scenario

145 views Asked by At

I have a problem and I wanted to create an algorithm to solve it. But I am wondering if my computation is right or I should improve it. This is the algo problem:

Create an algorithm that will compute for the grade of a student. The grade is equal to one-third of the minor exam and two thirds of the major exam. Print the student grade.

The algorithm I created is:

  1. Read the grades.
  2. Compute the midterm and minor grade using the following formula:
    grade = 1/3 * minor exam + 2/3 * major exam.
  3. print the grade

I don't know if my formula is correct.

1

There are 1 answers

1
amit On

I don't know if my formula is correct.

Mathematically speaking - this is indeed the formula for the problem you describe. However, note that in many languages, 1/3 * minor exam + 2/3 * midterm exam will be parsed as integer arithmetic operations, and that will lead to wrong answer (always 0).

The reason is, in integer arithmetic, when calculating a/b, the returned answer is floor(a/b) (where floor(.) is the closest not higher integer).

To make sure this does not happen - make sure to convert your number to floating points, and use floating points arithmetics - while they have their inaccuracy issues as well, this is seldom a problem when dealing with such a small formula and with relatively low numbers (in absolute value).