Splitting Things in Half

It’s pretty safe to avoid your first instinct when it comes to dividing two integers. That first instinct is most likely to typecast the int values as float. That works, and many times it can be the best solution, but it’s not always the solution.

When you deal in integer values, and those values must be split, you typically ignore anything left over — the remainder. So 13 divided by 2 is going to equal either 6 or 7, take your pick. You don’t want to split hairs — or integers.

For example, consider you have a burning desire to split a string of text in two. Strings with an even length split evenly. Strings with an odd length don’t split evenly; you can’t have a string with half a letter in it.

In the end, you manipulate an integer value without regard for fractions.

The simple way to split an int value in twain is to divide it by 2. Yes, division is normally performed with floating point values. Even when dividing integers, the result often ends up being a float. Feel free to disregard that thinking for a moment and behold this sample code:

#include <stdio.h>

int main()
{
    int alpha = 29;

    printf("29 divided by 2 is %d.\n",alpha/2);

    return(0);
}

Here’s the output:

29 divided by 2 is 14.

And, of course, that answer won’t get you an ‘A’ on human math quiz, but it’s how the computer deals with dividing two int values. It’s also sufficient for splitting a string in two; 14 characters of a 29-character string is good enough for “half.”

To get the true result, you need to make two modifications.

First, at least one of the values in the equation alpha/2 must be a floating point value, a real number.

Second, you need to modify the printf() statement to use the %f conversion character.

Solving the first problem can be done in several ways. The most obvious is to change variable alpha from an int to a float at Line 5:

float alpha = 29;

Or you can typecast either the variable alpha or the immediate value 2 in the printf() function, thus:

printf("29 divided by 2 is %f.\n",(float)alpha/2);

Or this:

printf("29 divided by 2 is %f.\n",alpha/(float)2);

You see above that I’ve already addressed the second modification, which is changing the %d to %f. Actually, I prefer to use %.1f for this problem, which yields the following output:

29 divided by 2 is 14.5.

That result isn’t going to help you when it comes to printing half a string of text, but it’s one way to solve the problem.

Leave a Reply