C Tutorial (20) : C functions for MATH

This tutorial extends your knowledge of built-in functions to the numeric functions. C  built-in numeric functions supply routines that you don’t have to write yourself.

A lot of C’s built-in math functions are highly technical—not that their uses are difficult, but their purposes might be. Unless you need trigonometric and advanced math functions, you might not find a use for many of the functions described in this tutorial.

All the functions this tutorial describes require the use of the math.h header file. Be sure to include math.h along with stdio.h if you use a math function.

The floor() and ceil() functions are called the floor and ceiling functions, respectively. They “push down” and “push up” nonintegers to their next-lower or next-higher integer values. For example, if you wanted to compute how many dollar bills were in a certain amount of change (that includes dollars and cents), you could use floor() on the amount. The following code does just that:

change = amtPaid – cost; //These are all floating-point values 
dollars = floor(change);

Note : Although ceil() and floor() convert their arguments to integers, each function returns a float value. That’s why the dollars variable was printed using the %f conversion code.

The ceil() function (which is the opposite of floor()) finds the next-highest integer. Both ceil() and floor() work with negative values, too, as the following few lines show:

lowVal1 = floor(18.5); // Stores 18.0 
lowVal2 = floor(-18.5); // Stores -19.0 
hiVal1 = ceil(18.5); // Stores 19.0 
hiVal2 = ceil(-18.5); // Stores =18.0

Note : The negative values make sense when you think about the direction of negative numbers. The next integer down from –18.5 is –19. The next integer up from –18.5 is – 18.

 

The fabs() function returns the floating-point absolute value. When you first hear about absolute value, it sounds like something you’ll never need. The absolute value of a number, whether it is negative or positive, is the positive version of the number. Both of these printf() functions print 25:

printf("Absolute value of 25.0 is %.0f.\n", fabs(25.0)); 
printf("Absolute value of -25.0 is %.0f.\n", fabs(-25.0));

Note : The floating-point answers print without decimal places because of the .0 inside the %f conversion codes.

Absolute values are useful for computing differences in ages, weights, and distances.

The pow() function raises a value to a power, and the sqrt() function returns the square root of a value.

Note : You can’t compute the square root of a negative number. The fabs() function can help ensure that you don’t try to do so by converting the number to a positive value before you compute the square root.

x = pow (4,6);                                x = 4*4*4*4*4*4

x = sqrt (value);                            x = (value)^(1/2)

printf("10 raised to the third power is %.0f.\n", pow(10.0, 3.0)); 
printf("The square root of 64 is %.0f.\n", sqrt(64));

Here is the output of these printf() functions:
10 raised to the 3rd power is 1000. 
The square root of 64 is 8.

 

Trigonometric and logarithmic functions

 

c_tan_log

Tip : If you want to supply an argument in degrees instead of radians, you can convert from degrees to radians with this formula:

radians = degrees * (3.14159 / 180.0);

 

Getting Random numbers

For games and simulation programs, you often need to generate random values. C’s built-in rand() function does just that. It returns a random number from 0 to 32767. The rand() function requires the stdlib.h (standard library) header file. If you want to narrow the random numbers, you can use % (the modulus operator) to do so. The following expression puts a random number from 1 to 6 in the variable dice:

dice = (rand() % 5) + 1;             /* From 1 to 6 */

Note : Because a die can have a value from 1 to 6, the modulus operator returns the integer division remainder (0 through 5), and then a 1 is added to produce a die value.

You must do one crazy thing if you want a truly random value.

To seed the random number generator means to give it an initial base value from which the rand() function can offset with a random number. Use srand() to seed the random number generator. The number inside the srand() parentheses must be different every time you run the program, unless you want to produce the same set of random values.

The trick to giving srand() a different number each run is to put the exact time of day inside the srand() parentheses. Your computer keeps track of the time of day, down to hundredths of a second. So first declare a time variable, using the time_t declaration, and then send its address (using the & character at the front of the variable name) to the srand() function.

Note : Many simulations and scientific studies need to repeat the same set of random numbers. rand() will always do that if you don’t seed the random number generator.

You must include time.h before seeding the random number generator with the time of day.

/* This program rolls two dice and presents the total. 
   It then asks the user to guess if the next total will be 
   higher, lower, or equal. It then rolls two more dice and 
   tells the user how they did. */

#include <stdio.h> 
#include <string.h> 
#include <time.h> 
#include <ctype.h>

main()
{
int dice1, dice2; 
int total1, total2; 
time_t t;

char ans;
//Remember that this is needed to make sure each random number generated is different

srand(time(&t));
//This would give you a number between 0 and 5, so the + 1 makes it 1 to 6

dice1 = (rand() % 5) + 1; 
dice2 = (rand() % 5) + 1; 

total1 = dice1 + dice2;

printf("First roll of the dice was %d and %d, ", dice1, dice2); 
printf("for a total of %d.\n\n\n", total1);

do {
puts("Do you think the next roll will be "); 
puts("(H)igher, (L)ower, or (S)ame?\n"); 
puts("Enter H, L, or S to reflect your guess.");
scanf(" %c", &ans); 
ans = toupper(ans);
} while ((ans != 'H') && (ans != 'L') && (ans != 'S'));

// Roll the dice a second time to get your second total
dice1 = (rand() % 5) + 1; 
dice2 = (rand() % 5) + 1; 
total2 = dice1 + dice2;


// Display the second total for the user
printf("\nThe second roll was %d and %d, ", dice1, dice2); 
printf("for a total of %d.\n\n", total2);

// Now compare the two dice totals against the user's guess 
// and tell them if they were right or not.

if (ans == 'L')
{
if (total2 < total1)
{
printf("Good job! You were right!\n"); 
printf("%d is lower than %d\n", total2, total1);
}
else
{
printf("Sorry! %d is not lower than %d\n\n", total2, total1);
}
}
else if (ans == 'H')
{
if (total2 > total1)
{
printf("Good job! You were right!\n"); 
printf("%d is higher than %d\n", total2, total1);
}
else
{
printf("Sorry! %d is not higher than %d\n\n", total2, total1);
}
}
else if (ans == 'S')
{
if (total2 == total1)
{
printf("Good job! You were right!\n");
printf("%d is the same as %d\n\n", total2, total1);
}
else
{
printf("Sorry! %d is not the same as %d\n\n", total2, total1);
}
}
return(0);
}

 

functions for strings < Prev                                                               Next > Array

 

Advertisements

2 comments

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