2. Numbers

Checking Whether a String Is a Valid Number

Comparing Floating-Point Numbers

Rounding Floating-Point Numbers

Converting Between Binary and Decimal

Operating on a Series of Integers

Working with Roman Numerals

Generating Random Numbers

//------------------------------------------------------------------
#include <stdlib.h> // rand() srand()

...

/*
    rand() function is not guaranted to produce random values
*/

int random;
  
// the same value between 0 and RAND_MAX
// for every run
random = rand();

...

//------------------------------------------------------------------
...

float random;

// the same value between 0 and 1.0
// for every run
random = (float) rand() / RAND_MAX;

...

//------------------------------------------------------------------
...

#define N 42

...

int random;

// the same value between 0 and N -1
// for every run
random = (int)( N * (double)rand() / (RAND_MAX + 1.0) );

...

Generating Different Random Numbers

//------------------------------------------------------------------
#include <stdlib.h> // rand() srand()
#include <time.h> // time()

...

int random;

// seeds a new sequence of random number
srand(time(NULL));

// a different value between 0 and RAND_MAX
// for every run
random = rand();

...

Making Numbers Even More Random

//------------------------------------------------------------------
/*
    under Linux /dev/random or /dev/urandom
*/

#include <stdio.h> // FILE *, fopen(), fread(), fclose()

...

FILE * fp;

unsigned int random;

if ((fp = fopen("/dev/random","r")) == NULL) {
  perror("fopen");
  exit(1);
}

fread(&random, sizeof(random), 1, fp);
printf("random number %u from /dev/random\n", random);

fclose(fp);

...

//------------------------------------------------------------------

Generating Biased Random Numbers

Doing Trigonometry in Degrees, not Radians

Calculating More Trigonometric Functions

Taking Logarithms

Multiplying Matrices

Using Complex Numbers

Converting Between Octal and Hexadecimal

Putting Commas in Numbers

Printing Correct Plurals

Program: Calculating Prime Factors