Code::Blocks simple guide – simple mathematical operations II


In our previous discussion, we stopped at an example of implementing mathematical operations. However, I mentioned that there were some mistakes in the code. Did you managed to spot those mistakes?


I’m sure you can easily detect the first one. The results for the line

e = a / b


yields e = 0 in the terminal. With a = 2 and b = 3, the output on the terminal is clearly wrong. Why does this happen then?


The cause of this error is due to the fact that we have declare the variable “e” as integer. If we perform this calculation on a calculator, we will get e = 0.66667. However, the code only retrieved the first number before the decimal point and thus results in a wrong output. In order to rectify this, we just need to change the variable type of “e” to real number.


At the same time, we also need to convert variable “a” and “b” to real numbers before performing the mathematical operation. We do this by using the command

real(a) and real(b)


To allow for comparison between the previous “wrong” output to the one obtained after the modification, we will now attribute the same operation to a new variable “g” such that:

 g = real(a) / real(b)


The results obtained after executing the code will be given at the end of this discussion. I will now discuss about the second error in the previous code. You may well expect it by now. The error is with the output of variable “f”. The second term on the right hand side of

f = a**2 + b**(3/2)


yields a non-integer value. Therefore, using an integer type variable is not correct to begin with. In that case, we need to declare a real type variable for this operation.


Other than having to change the variable type as we did for the first error above, we also need to pay attention to the following differences:

h = real(a)**2 + real(b)**(3/2) 

h = real(a)**2.0 + real(b)**(3.0/2.0) 


The first line will not give you the correct result. Only the second line returns a correct value. Since variable “h” is of a real type, therefore the exponents should also be in real numbers.


The following is the output printed on the terminal after amendments to the previous main.f95 code. The modified version of the Fortran code can be found here. Note that the wrong values for “e” and “f” were retained for comparison to the correct “g” and “h” outputs.