C Programming Tutorial 13 – Basic Type Casting

Don’t forget to read the last blog about arithmetic expressions! Are you new here? Start at the beginning!

Let’s create another program to solve another math problem. This one is going to be a little less serious, because serious math can be boring sometimes.

We work for a chicken company who wants us to write software that tells them how many dozen eggs they produce in a day. So each night, a guy enters in how many eggs they have, and then the output is how many dozens that is. A dozen is just 12, so all we really have to do is divide the number by 12. Pretty simple, but it will illustrate a good programming point.

We are going to make a variable to store the number of eggs, but what data type do we want it to be? Well double would allow us to have a fraction of an egg, which doesn’t make a lot of sense because they are not going to sell partial eggs. So integer will work fine.

Now to calculate the dozen, all we have to do is divide by 12.

The reason we want dozen to be of the data type double is because we could have fractions of a dozen. For example, we could have a half dozen (.5 dozen).

When Running into Issues…

We can try this with a number like 24 and you can see that we get 2. This is correct! So it seems like our program is working. But wait…what happens if I put 18 eggs?

The answer is 1 dozen  What the heck?!

The problem here is that when we look at the line of code: double dozen = eggs / 12; we are dividing an integer by an integer. Whenever we divide two integers in C, we are always going to get an integer as a result.

There are two ways we can fix this. The first, is add .0 to the twelve. In this situation we no longer have two integers, so C will do this operation and give us a double value.

So the lesson learned is that whenever you are doing arithmetic with an integer and a double, the double takes precedence. Meaning, C makes the result a double, not an integer.

Try it and see what you get!

Type Casting

The second option is using what is known as type casting. Type casting is the process of changing the data type of something. This is the more sophisticated way of changing data types and will work in more situations, but sometimes the previous method works fine!

In this situation we are casting the eggs to be of double data type. Now, the result will be 1.5.

You need to be careful with type casting! If we do something like this:

The division gets evaluated as integer division, which gives us 1. Then, we convert 1 to a double and get 1.0.

So be careful and do lots of testing when working with type casting!

In the next blog we are talking about working with strings! Don’t miss it!

Did you know that each one of these blogs has a video with it? Check out this one below!

Leave a Reply

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