Learning to program (ii) – an interactive Julia program

In the last post we created a simple program to calculate the approximate age of a particular species of tree, the Silver Maple, given the circumference of the tree.

d = 94.25 / pi
g = 3.0
age = d * g
println(age)

How is that program improved upon? Firstly by adding some input for the user to allow for any tree circumference to be entered by the programs user. This is achieved by first prompting the user, (because otherwise they would not know what value to input), and then reading in the value typed by the user. Note that as the program is now using a changing value for the circumference, the value 94.25 should be replaced with c, the value input by the user.

println("Enter the circumference of the tree: ")
c = parse(chomp(readline()))
d = c / pi 
g = 3.0 
age = d * g 
println(age)

We should add some things that make the input and output easier to decipher. The units are helpful, in this case inches, and the time units for the output:

println("Enter the circumference of the tree (inches): ") 
c = parse(chomp(readline())) 
d = c / pi 
g = 3.0 
age = d * g 
println("The tree is ", age, " years old")

When the program is run, it looks like this:

Enter the circumference of the tree (inches):
98
The tree is 93.58310653803446 years old

Of course the answer has way too many decimal places to be useful. So the println statement can be modified to round the answer to 2 decimal places:

println("Enter the circumference of the tree (inches): ") 
c = parse(chomp(readline())) 
d = c / pi 
g = 3.0 
age = d * g 
println("The tree is ", round(age,2), " years old")

Now the answer is much more user friendly:

Enter the circumference of the tree (inches):
98
The tree is 93.58 years old

Now of course this program only works with Silver Maples, so it’s not that useful. In the next post, we’ll see how to make the program a little more broader in scope.

 

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s