Originally published by Robert Beisert at fortcollinsprogram.robert-beisert.com

Linux + C – Doing the Math II

We’ve looked at the basics of performing basic math in C, but there are a few more things we should discuss before we write any code.

Data Types

We know that there are many different kinds of numbers. For example, we have signed numbers (which can be positive or negative) and unsigned numbers (which are assumed to be positive). The most relevant data types we deal with are:

int      Signed Integer between -(2^31) and (2^31-1)

uintX_t      Unsigned integer between 0 and (2^X-1)

Example: uint8_t is an 8-bit unsigned integer

float      Signed floating point number (32-bits)

double      Signed floating point number (54-bits)

That’s basically one data type for every conventional use.

Note: the uintX_t data types are defined in <stdint.h>.

Functions

There are lots of functions we can perform for which we don’t really have symbols. For example, we can perform exponential functions (e^x), power functions (x^y), and the trig functions.

All of these and more are defined in the standard library header <math.h>. I recommend that you look them up here before you attempt to use them.

do_math.c

Now we put all the things we just learned into practice. Using the vim text editor, create a file named do_math.c with the following code:


//Compile with command:
//    gcc -o do_math do_math.c -lm
//Otherwise, we don't get the pow() function

#include <stdio.h>
#include <stdint.h>
#include <math.h>

int main(int argc, char *argv[])
{
int x = 0;
double y = 0;
float z = 0;

x = 3 + 4;
y = 3 - 4;
z = x * y;

printf("X: %d\nY: %f\nZ: %f\n", x, y, z);

x = -z / (y + x);
y = y * z;
z = (int) pow(y, 2);

printf("X: %d\nY: %f\nZ: %f\n", x, y, z);

return 0;
}

When you’re done, compile and run the program with the command:

gcc -o do_math do_math.c -lm

./do_math

Check the output and compare it to the code. Make sure you understand how we got the numbers we did.

Further Learning

Change the equations and see how the results change. In particular, you should try the following:

  • Perform the modulo (%) operation on two integers
  • Perform division between two integers which you KNOW won’t come out evenly. For example, try int x = 4/6
  • Replace all ints with uint32_ts and see how the results change