Basics of Common Math Functions in C Programming

Not everyone is going to employ their C language programming skills to help pilot a rocket safely across space and into orbit around Titan. No, it’s more likely that you’ll attempt something far more down-to-earth. Either way, the work will most likely be done by employing math functions.

Function #include What It Does
sqrt() math.h Calculates the square root of a floating-point value
pow() math.h Returns the result of a floating-point value raised to a certain power
abs() stdlib.h Returns the absolute value (positive value) of an integer
floor() math.h Rounds up a floating-point value to the next whole number (nonfractional) value
ceil() math.h Rounds down a floating-point value to the next whole number

All the functions listed, save for the abs() function, deal with floating-point values. The abs() function works only with integers.

You can look up function references in the man pages, accessed via Code::Blocks or found online or at the command prompt in a Unix terminal window.

Math Mania Mangled is littered with a smattering of math functions. The compiler enjoys seeing these functions, as long as you remember to include the math.h header file at Line 2.

MATH MANIA MANGLED

#include <stdio.h>
#include <math.h>
int main()
{
 float result,value;
 printf("Input a float value: ");
 scanf("%f",&value);
 result = sqrt(value);
 printf("The square root of %.2f is %.2f\n",
value,result); result = pow(value,3); printf("%.2f to the 3rd power is %.2f\n",
value,result); result = floor(value); printf("The floor of %.2f is %.2f\n",
value,result); result = ceil(value); printf("And the ceiling of %.2f is %.2f\n",
value,result); return(0); }

Exercise 1: Create a new project using the source code from Math Mania Mangled. Be aware that the printf() functions in the Listing were wrapped so that they’re split between two lines; you don’t need to wrap them in your source code. Build the project. Run it and try various values as input to peruse the results.

Exercise 2: Write a program that displays the powers of 2, showing all values from 20 through 210. These are the Holy Numbers of Computing.

  • The math functions listed are only a small sampling of the variety available.

  • Generally speaking, if your code requires some sort of mathematical operation, check the C library documentation, the man pages, to see whether that specific function exists.

  • On a Unix system, type man 3 math to see a list of the C library’s math functions.

  • The ceil() function is pronounced “seal.” It’s from the word ceiling, which is a play on the floor() function.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.