1.4converting a C Program to C++
2014-04-17 本文已影响0人
Roy_he
C Program:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIDES 6
#define R_SIDE (rand() % SIDES + 1)
int main(void)
{
int n_dice = 2;
int d1, d2, trials, j;
int* outcomes =calloc (sizeof(int), n_dice * SIDES +1);
srand(clock());
printf ("\nEnter number of trials: ");
scanf("%d", &trials);
for (j = 0; j < trials; ++j)
outcomes[(d1 = R_SIDE) +( d2 = R_SIDE)]++;
printf( "probability\n");
for (j = 2; j < n_dice * SIDES + 1; ++j)
printf( "j = %d p = %lf\n" , j , (double)(outcomes[j])/trials);
}
C++ Improvements
-NB some of these are adopted in modern C
-Different libraries most old C libraries still
-available – usually as c....
-Inline - replaces code macro – benefit?
-Rest of line comments
C++ Program
#include <iostream> //drops .h still available
#include <cstdlib>
#include <ctime>
using namespace std;
const int sides = 6; //replaces many sharp defines
inline int r_sides(){ return (rand() % sides + 1); }
int main(void)
{
const int n_dice = 2;
int d1, d2;
srand(clock()); //why?
cout << "\nEnter number of trials: ";
int trials;
cin >> trials; //compare to scanf
int* outcomes = new int[n_dice * sides +1]; TYPE* s;
for (int j = 0; j < trials; ++j)
outcomes[(d1 = r_sides()) +( d2 = r_sides())]++;
cout << "probability\n";
for (int j = 2; j < n_dice * sides + 1; ++j)
cout << "j = " << j << " p = "<<
static_cast<double>(outcomes[j])/trials<< endl;
}
C Program
#include <stdio.h>
#include <math.h>
double fcn(double x)
{ return x * x - 1; }
double fcn2(double x)
{ return x * x * x * x * x - exp( x ) -2; }
double root_find(
double f(double), /* function with root */
double a, double b, /* interval (a, b) with root */
double eps, /* accuracy */
double *root /* root --output*/
)
{
if ( b - a < eps){
*root = (b + a)/2.0;
return f(*root);
}
else if ( f(a)* f( (b + a)/2) <= 0)
return root_find(f, a, (b+a)/2, eps, root);
else
return root_find(f, (b+a)/2, b, eps, root);
}
int main(void)
{
double x;
printf("Root Finder\n");
root_find(fcn, 0.0, 4.0, 0.00001, &x);
printf("root is at %g with residual %g \n", x, fcn(x));
root_find(fcn2, 0.0, 14.0, 0.00001, &x);
printf("root is at %g\n", x);
return 0;
}
C++ Program:
#include <iostream>
#include <cmath>
using namespace std;
inline double fcn(double x)
{
return x * x -1;
}
inline double fcn2(double x)
{
return x * x * x * x * x - exp(x) - 2;
}
double root_find(
double f(double),/*function with root*/
double a, double b,/*interval (a, b) with root*/
double eps,/*accuracy*/
double *root
)
{
if(b - a < eps){
*root = (b + a)/2.0;
return f(*root);
}
else if(f(a)*f((b + a)/2 <= 0))
return root_find(f, a, (b + a)/2, eps, root);
else
return root_find(f, (b + a)/2, b, eps, root);
}
int main()
{
double x;
cout << "Root Finder" << endl;
root_find(fcn, 0.0, 4.0, 0.000001, &x);
cout << "root is at " << x << "with residual " << fcn(x) << endl;
root_find(fcn2, 0.0, 14.0, 0.000001, &x);
cout << "root is at " << x << endl;
return 0;
}