Created
February 29, 2012 17:35
-
-
Save AstDerek/1942806 to your computer and use it in GitHub Desktop.
Imperative, functional, OOP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define IMPERATIVE | |
#ifdef IMPERATIVE | |
#include <iostream> | |
using namespace std; | |
int main (int narg, char *varg[]) { | |
if (narg != 4) { | |
cout << "Usage:\n program_name [number] [number] [number]\n"; | |
return 0; | |
} | |
cout << "Average:\n" << (atof(varg[1]) + atof(varg[2]) + atof(varg[3]))/3 << "\n"; | |
return 0; | |
} | |
#endif | |
#ifdef FUNCTIONAL | |
#include <stdio.h> | |
#include <stdlib.h> | |
double sum (double a, double b) { | |
return a + b; | |
} | |
double divide (double a, double b) { | |
return a/b; | |
} | |
void print (char *a) { | |
cout << a << endl; | |
} | |
int main (int narg, char *varg[]) { | |
double a = 0, b = 0, c = 0, | |
average = 0; | |
if (narg != 4) { | |
print("Usage:" << endl << "program_name [number] [number] [number]" << endl); | |
return 0; | |
} | |
print( | |
"Average: " << | |
divide( | |
sum( | |
atof(varg[1]), | |
sum( | |
atof(varg[2]), | |
atof(varg[3]) | |
) | |
), | |
3 | |
) | |
); | |
return 0; | |
} | |
#endif | |
#ifdef OOP | |
#include <iostream> | |
using namespace std; | |
class Sum { | |
double sum, total; | |
public: | |
Sum () { | |
sum = 0; | |
total = 0; | |
} | |
Sum add (double a) { | |
sum += a; | |
total++; | |
return *this; | |
} | |
Sum operator+ (double a) { | |
return add(a); | |
} | |
double average () { | |
return total ? sum/total : 0; | |
} | |
}; | |
int main (int narg, char *varg[]) { | |
Sum sum; | |
if (narg != 4) { | |
cout << "Usage:\nprogram_name [number] [number] [number]\n"; | |
return 0; | |
} | |
/** | |
* Method chaining | |
* | |
* cout << "Average:\n" << (sum + atof(varg[1]) + atof(varg[2]) + atof(varg[3])).average() << "\n"; | |
*/ | |
sum.add(atof(varg[1])); | |
sum.add(atof(varg[2])); | |
sum.add(atof(varg[3])); | |
cout << "Average:\n" << sum.average() << "\n"; | |
return 0; | |
} | |
#endif |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment