Wednesday, September 19, 2018

Homework 7

Factorials
/* This program compares a recursive function and */
/* a nonrecursive function for computing factorials. */
#include <stdio.h>
#include <math.h>
int main(void)
#define PI 3.141593
#define e 2.718281
{
/* Declare variables and function prototypes. */
double n;
double factorial(double k);
double factorial_r(double k);
double n_fact(double k);
/* Get user input. */
printf("Enter positive integer: \n");
scanf("%lf",&n);
/* Compute and print factorials. */
printf("Nonrecursive: %lf! = %lf \n",n,factorial(n));
printf("Recursive: %lf! = %lf \n",n,factorial_r(n));
printf("Sterling: %lf! = %lf \n",n,n_fact(n));
/* Exit program. */
return 0;
}
/* This function computes a factorial with a loop. */
double factorial(double k)
{
/* Declare variables. */
double j;
long term;
/* Compute factorial with multiplication. */
term = 1;
for (j=2; j<=k; j++)
term *=j;
/* Return factorial value. */
return term;
}
/* This function computes a factorial recursively. */
double factorial_r(double k)
{
/* Use recursive reference until k=0. */
if (k == 0)
return 1;
else
return k*factorial_r(k-1);
}
/* This function computes a factorial using Sterling Formula*/
double n_fact(double n)
{
return sqrt(2*PI*n)*pow(n/e, n);
}

Random Dice Rolls
/* This program generates and prints ten random */
/* integers between user-specified limits. */
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
/* Declare variables and function prototype. */
unsigned int seed;
int a=1, b=6, k, dice1, dice2, d;
double dice_percent, dicecounter;
int rand_int(int a,int b);
/* Get seed value and interval limits. */
printf("Enter a positive integer seed value: \n");
scanf("%u",&seed);
printf("Enter the number of rolls of the dice to simulate: \n");
scanf("%u",&d);
srand(seed);
/* Generate and print ten random numbers. */
printf("\nRandom dice rolls of two dice: \n");
for (k=1; k<=d; k++)
{
dice1 = rand_int(a,b);
dice2 = rand_int(a,b);
if (dice1 + dice2 == 8)
{
dicecounter++;
}
printf("\nRoll #%i: %i, %i\n", k , dice1, dice2);
}
dice_percent = (dicecounter / d) * 100;
printf("\nPercentage of times that the values of the dice equaled 8: %.2f ", dice_percent);
/* Exit program. */
return 0;
}
/* This function generates a random integer */
/* between specified limits a and b (a<b). */
int rand_int(int a,int b)
{
return rand()%(b-a+1) + a;
}

No comments:

Post a Comment