![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Programming Guru
![]() Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 5
![]() |
my 1st programming goal was to write a four-function calculator in C, C++, Java, and Python. here are the first three.
in Java: //import the java input/output library
import java.io.*;
//class that contains the math functions
class MFunctions {
//result variable
double result;
String inData;
//constructor...not much here...
//remnant from the days when the user input was supplied to
//this class as an argument
//MFunctions() {
//}
//addition method
double add(double v1, double v2) {
result = (v1 + v2);
return result;
}
//subtraction method
double subtract(double v1, double v2) {
result = (v1 - v2);
return result;
}
//multiplication method
double multiply(double v1, double v2) {
result = (v1 * v2);
return result;
}
//division method
double divide(double v1, double v2) {
result = (v1 / v2);
return result;
}
//clear method
double clear(double v1) {
result = v1;
return result;
}
//square method
double square(double v1) {
result = (v1 * v1);
return result;
}
//square root method
double sqroot(double v1) {
result = Math.sqrt(v1);
return result;
}
//"power of" method
//doesn't quite work right when power is a floating-point input
double power(double v1, double v2, double v3) {
int i = 1;
//get initial input
//v3 remains as the initial input
//so that v1 can be accurately calculated
//increment loop until power is reached
while (i < v2) {
v1 = (v1 * v3);
i++;
}//while loop ends here
result = v1;
return result;
}//"power-of" method ends here
}//MFunctions class ends here
//class containing the "main" method
class FFC {
public static void main(String[] args) throws IOException {
//generic input variable
String inData, userChoice;
//user-defined input variables
double initialV, nextV;
double x = 0;
//boolean variable for quitting loop
boolean sentV = false;
//initiate java IO library
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
//instantiate object of "MFunctions" class
MFunctions mf = new MFunctions();
//initial user input
System.out.println("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
System.out.println("Welcome to the currently expanding calculator simulation!");
System.out.print("When prompted for a math function choice ");
System.out.print("please type either: \nthe number of your choice, ");
System.out.println("\nor the symbol beside the number.");
System.out.println("\nIf you receive a result of either: ");
System.out.println("'NaN' or 'infinity'");
System.out.println("OR repeated calculations reach the UNEXPECTED result of either '1' or '0'");
System.out.println("Your calculations have exceeded the bounds of the java language.");
System.out.println("\n\nEnter a number.\n\n\n\n\n\n\n\n\n\n\n");
inData = br.readLine();
initialV = Double.parseDouble(inData);
//quitting loop
while (sentV != true) {
//determine the math function from the user
System.out.println("\n\n\nChoose a basic math function.\n");
System.out.println("1. +\t(addition)");
System.out.println("2. -\t(subtraction)");
System.out.println("3. *\t(multiplication)");
System.out.println("4. /\t(division)");
System.out.println("5. c\t(clear)");
System.out.println("6. =\t(equals/finished)");
System.out.println("7. s\t(square)");
System.out.println("8. sq\t(square root)");
System.out.println("9. pw\t(power of)");
System.out.println("\n\n\n\n\n");
userChoice = br.readLine();
//if user chooses to add...
if (userChoice.trim().startsWith("+") || userChoice.trim().startsWith("1") ) {
//get next number from user
System.out.println("\n\n" + initialV + " Plus?\n\n");
inData = br.readLine();
nextV = Double.parseDouble(inData);
//print current value and assign that value to initial value
//this is repeated in the following...
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("Current value is: " + mf.add(initialV, nextV) + "\n");
initialV = mf.add(initialV, nextV);
}//end user add choice
//if user chooses to subtract
if (userChoice.trim().startsWith("-") || userChoice.trim().startsWith("2") ) {
System.out.println("\n\n" + initialV + " Minus?\n\n");
inData = br.readLine();
nextV = Double.parseDouble(inData);
//see above comment in add choice
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("\n\nCurrent value is: " + mf.subtract(initialV, nextV) + "\n");
initialV = mf.subtract(initialV, nextV);
}//end user subtract choice
//if user chooses to multiply
if (userChoice.trim().startsWith("*") || userChoice.trim().startsWith("3") ) {
System.out.println("\n\n" + initialV + " Multiplied by?\n\n");
inData = br.readLine();
nextV = Double.parseDouble(inData);
//see above comment in add choice
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("\n\nCurrent value is: " + mf.multiply(initialV, nextV) + "\n");
initialV = mf.multiply(initialV, nextV);
}//end user multiplication choice
//if user chooses to divide
if (userChoice.trim().startsWith("/") || userChoice.trim().startsWith("4") ) {
System.out.println("\n\n" + initialV + " Divided by?\n\n");
inData = br.readLine();
nextV = Double.parseDouble(inData);
//see above comment in add choice
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("\n\nCurrent value is: " + mf.divide(initialV, nextV) + "\n");
initialV = mf.divide(initialV, nextV);
}//end user division choice
//if user chooses to clear
if (userChoice.trim().startsWith("c") || userChoice.trim().startsWith("5") ) {
System.out.println("\n\n\n\n\n\n\n\n\n");
System.out.println("The new initial value is zero.\n\n");
System.out.println("Enter the new initial value.");
System.out.println("\n\n\n\n\n");
inData = br.readLine();
initialV = Double.parseDouble(inData);
System.out.println("\n\n\n\n\n\n\n\n\n");
System.out.println("\n\nCurrent value is: " + mf.clear(initialV) + "\n");
initialV = mf.clear(initialV);
}//end user clear choice
//if user chooses square
if (userChoice.trim().startsWith("s") || userChoice.trim().startsWith("7") ) {
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("\n\nCurrent value is: " + mf.square(initialV) + "\n");
initialV = mf.square(initialV);
}//end user square choice
//if user chooses square root
if (userChoice.trim().startsWith("sr") || userChoice.trim().startsWith("8") ) {
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("\n\nCurrent value is: " + mf.sqroot(initialV) + "\n");
initialV = mf.sqroot(initialV);
}//end user square root choice
//if user chooses "power-of"
final double thirdV = initialV;
if (userChoice.trim().startsWith("pw") || userChoice.trim().startsWith("9") ) {
System.out.println(initialV + "\n\nTo the power of?");
inData = br.readLine();
nextV = Double.parseDouble(inData);
System.out.println("\n\n\n\n\n\n\n\n\n\n");
System.out.println("\n\nCurrent value is: " + mf.power(initialV, nextV, thirdV) + "\n");
initialV = mf.power(initialV, nextV, thirdV);
}//end user "power-of" choice
//if user chooses to quit
if (userChoice.trim().startsWith("=") || userChoice.trim().startsWith("6") ) {
sentV = true;
}//end user final quitting choice
}//while loop ends here
//final value printed on-screen for user
System.out.println("\n\n\n\n\n\n\n");
System.out.println("The final result is:\t" + initialV);
System.out.println("\n\n\n\n\n\n\n");
}//main ends here
}//class ends herein C:
//C standard I/O library
#include <stdio.h>
//creating my own boolean types for clarity
#define true 1
#define false 0
//global variable for dynamic calculations
double dCurrentV = 0;
//function declarations
double add(double x, double y);
double sub(double x, double y);
double mlt(double x, double y);
double div(double x, double y);
int clear(void);
//begin main
int main(void)
{
//user-defined operation choice
int iOpChoice;
//boolean do-while loop sentinal value
int iSentVal = true;
//user-defined next number choice
double dNext;
//opening marquee
printf("\n\n\n\n\n\n\n\n\n\n");
printf(" ***********************************************\n");
printf(" * *\n");
printf(" * *\n");
printf(" * *\n");
printf(" * *\n");
printf(" * The four-function calculator simulation *\n");
printf(" * written in C *\n");
printf(" * b hancock 2004 *\n");
printf(" * *\n");
printf(" * *\n");
printf(" ***********************************************\n\n\n\n");
printf("\n\n\n\n\n");
clearpoint:;
printf("\n\n\nFirst number?");
scanf("%lf", &dCurrentV);
//do=while loop begins here
do
{
printf("\n\n\nPlease choose a function from the list\n\n\n");
printf("1.\tAddition\t\t4.\tDivision\n\n");
printf("2.\tSubtraction\t\t5.\tClear (Reset)\n\n");
printf("3.\tMultiplication\t\t6.\tQuit\n\n\n\n");
scanf("%d", &iOpChoice);
//switch starts here
switch(iOpChoice)
{
case 1:
printf("add?");
scanf("%lf", &dNext);
dCurrentV = add(dCurrentV, dNext);
printf("\n\n\n\n");
printf("The current value is %lf", dCurrentV);
break;
case 2:
printf("subtract?");
scanf("%lf", &dNext);
dCurrentV = sub(dCurrentV, dNext);
printf("\n\n\n\n");
printf("The current value is %lf\n\n\n", dCurrentV);
break;
case 3:
printf("multiply by?");
scanf("%lf", &dNext);
dCurrentV = mlt(dCurrentV, dNext);
printf("\n\n\n\n");
printf("The current value is %lf\n\n\n", dCurrentV);
break;
case 4:
printf("divide by?");
scanf("%lf", &dNext);
dCurrentV = div(dCurrentV, dNext);
printf("\n\n\n\n");
printf("The current value is %lf\n\n\n", dCurrentV);
break;
case 5:
clear();
goto clearpoint;
break;
case 6:
iSentVal = false;
break;
default:
printf("Invalid input\n");
break;
} //switch ends here
}//do-while loop ends here
while(iSentVal != false);
return 0;
}//main ends here
//function definitions
double add(double x, double y)
{
double result;
result = (x + y);
return result;
}
double sub(double x, double y)
{
double result;
result = (x - y);
return result;
}
double mlt(double x, double y)
{
double result;
result = (x * y);
return result;
}
double div(double x, double y)
{
double result;
result = (x / y);
return result;
}
int clear(void)
{
dCurrentV = 0;
return dCurrentV;
}
//program ends herein C++: #include <iostream>
using namespace std;
class Func
{
public:
Func(double firstV);
~Func();
double add(double cValue);
double sub(double cValue);
double mlt(double cValue);
double div(double cValue);
int clr(double cValue);
private:
double cValue;
};
Func::Func(double firstV)
{
cValue = firstV;
}
Func::~Func()
{
}
double Func::add(double cValue)
{
double y;
cout<<"\n\n\nAdd?\n\n\n\n"<<endl;
cin>>y;
cValue = (cValue + y);
return cValue;
}
double Func::sub(double cValue)
{
double y;
cout<<"\n\n\nSubtract?\n\n\n\n"<<endl;
cin>>y;
cValue = (cValue - y);
return cValue;
}
double Func::mlt(double cValue)
{
double y;
cout<<"\n\n\nMultiply by?\n\n\n\n"<<endl;
cin>>y;
cValue = (cValue * y);
return cValue;
}
double Func::div(double cValue)
{
double y;
cout<<"\n\n\nDivided by?\n\n\n\n"<<endl;
cin>>y;
cValue = (cValue / y);
return cValue;
}
int Func::clr(double cValue)
{
cValue = 0;
return cValue;
}
int main()
{
cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"<<endl;
cout<<" *****************************************************\n";
cout<<" * *\n";
cout<<" * *\n";
cout<<" * *\n";
cout<<" * *\n";
cout<<" * The four-function calculator simulation *\n";
cout<<" * written in C++ *\n";
cout<<" * b hancock 2004 *\n";
cout<<" * *\n";
cout<<" * *\n";
cout<<" * *\n";
cout<<" * *\n";
cout<<" *****************************************************\n";
int uChoice1;
double cValue;
bool cont = true;
cout<<"\n\n\nInitial value?\n\n\n\n"<<endl;
cin>>cValue;
cout<<"\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"<<endl;
cout<<"The current value is "<<cValue<<"\n\n"<<endl;
Func ffc(cValue);
do
{
cout<<"\n\nPick a function.\n\n"<<endl;
cout<<"1.\tAddition\t4.\tDivision\n\n"<<endl;
cout<<"2.\tSubtraction\t5.\tClear\n\n"<<endl;
cout<<"3.\tMultiplication\t6.\tQuit.\n\n"<<endl;
cin>>uChoice1;
switch (uChoice1)
{
case 1:
cValue = ffc.add(cValue);
cout<<"\n\n\n\n\n\n\n\n\n\n";
cout<<"The current result is "<<cValue<<"\n\n\n"<<endl;
break;
case 2:
cValue = ffc.sub(cValue);
cout<<"\n\n\n\n\n\n\n\n\n\n";
cout<<"The current result is "<<cValue<<"\n\n\n"<<endl;
break;
case 3:
cValue = ffc.mlt(cValue);
cout<<"\n\n\n\n\n\n\n\n\n\n";
cout<<"The current result is "<<cValue<<"\n\n\n"<<endl;
break;
case 4:
cValue = ffc.div(cValue);
cout<<"\n\n\n\n\n\n\n\n\n\n";
cout<<"The current result is "<<cValue<<"\n\n\n"<<endl;
break;
case 5:
cValue = ffc.clr(cValue);
cout<<"\n\n\n\n\n\n\n\n\n\n";
cout<<"The value is now cleared to "<<cValue<<"\n\n\n"<<endl;
break;
case 6:
cont = false;
break;
default:
cout<<"\n\n\n\nInvalid input, please re-enter.\n\n";
continue;
}
}while(cont == true);
return 0;
}
__________________
i put on my robe and wizard hat... Have you ever heard of Plato, Aristotle, Socrates?...Morons. |
|
|
|
|
|
#2 |
|
Professional Programmer
Join Date: Jun 2004
Location: South Africa, Johannesburg
Posts: 301
Rep Power: 5
![]() |
Hmmm...in the C version, after you choose to clear the number, it asks you to enter a new value, but in the C++ one, it clears it to '0' and doesn't let you give a new value for it.
__________________
[SIGPIC][/SIGPIC] |
|
|
|
|
|
#3 |
|
Professional Programmer
Join Date: Jun 2004
Location: South Africa, Johannesburg
Posts: 301
Rep Power: 5
![]() |
not a problem, just like to pick out silly things
![]()
__________________
[SIGPIC][/SIGPIC] |
|
|
|
|
|
#4 |
|
Programmer
|
Some nice programs... How much you want to bet that the Python program will be one of the shortest ones
![]() Beeg |
|
|
|
|
|
#5 |
|
Professional Programmer
Join Date: Nov 2004
Posts: 250
Rep Power: 4
![]() |
That's a lot of bulk for not much functionality. For example, would you really want to fire this program up whenever you needed a calculator? Probably not, because it only works with two numbers and takes too much of the user's effort to handle even that. Of course, writing a parser that allows one to type expressions isn't a trivial task, which is why the Python program will be simplicity itself (just call eval on the input string).
If I might offer a suggestion in C: #include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define UNARY 0 /* Offset into actions for unary words */
#define BINARY 6 /* Offset into actions for binary words */
#define ACLEN 17 /* Total number of actions */
#define UNLEN 6 /* Total number of unary words */
#define BILEN 11 /* Total number of binary words */
static const char *actions[] = {
".", "sqrt", "sq", "not", "abs", "log",
"+", "-", "*", "/", "mod", "pow",
"<", "=", ">", "and", "or",
};
static long int stack[1024];
static int top = 0;
static void eval ( void );
static void gather ( void );
static void process ( const char *action );
static void do_unary ( const char *action );
static void do_binary ( const char *action );
static void die ( const char *msg );
static int is_valid ( const char *action, size_t offset, size_t limit );
int main ( void )
{
while ( 1 )
eval();
}
void eval ( void )
{
gather();
puts ( " ok" );
}
void gather ( void )
{
char buffer[BUFSIZ];
char *action;
char *end;
if ( fgets ( buffer, sizeof buffer, stdin ) == NULL )
die ( "Input error" );
for ( action = strtok ( buffer, " \t\n" );
action != NULL; action = strtok ( NULL, " \t\n" ) )
{
long int number;
/* Process a number or an action */
number = strtol ( action, &end, 0 );
if ( end > action )
stack[top++] = number;
else if ( is_valid ( action, 0, ACLEN ) )
process ( action );
else if ( strcmp ( action, "bye" ) == 0 )
exit ( EXIT_SUCCESS );
else
die ( "Input error" );
}
}
void process ( const char *action )
{
if ( is_valid ( action, UNARY, UNLEN ) )
do_unary ( action );
else if ( is_valid ( action, BINARY, BILEN ) )
do_binary ( action );
}
void do_unary ( const char *action )
{
long int result = 0;
long int a;
if ( top == 0 )
die ( "Stack underflow" );
a = stack[--top];
if ( strcmp ( action, "." ) == 0 ) {
printf ( "%ld ", a );
fflush ( stdout );
return;
}
else if ( strcmp ( action, "not" ) == 0 )
result = !a;
else if ( strcmp ( action, "sqrt" ) == 0 )
result = (long int)sqrt ( a );
else if ( strcmp ( action, "sq" ) == 0 )
result = a * a;
else if ( strcmp ( action, "abs" ) == 0 )
result = abs ( a );
else if ( strcmp ( action, "log" ) == 0 )
result = (long int)log ( a );
else
die ( "Invalid format" );
stack[top++] = result;
}
void do_binary ( const char *action )
{
long int result = 0;
long int a, b;
if ( top < 2 )
die ( "Stack underflow" );
b = stack[--top];
a = stack[--top];
if ( action[0] == '+' )
result = a + b;
else if ( action[0] == '-' )
result = a - b;
else if ( action[0] == '*' )
result = a * b;
else if ( action[0] == '/' ) {
if ( b == 0 )
die ( "Division by zero" );
result = a / b;
}
else if ( strcmp ( action, "mod" ) == 0 ) {
if ( b == 0 )
die ( "Division by zero" );
result = a % b;
}
else if ( strcmp ( action, "pow" ) == 0 )
result = (long int)pow ( a, b );
else if ( action[0] == '<' )
result = a < b;
else if ( action[0] == '=' )
result = a == b;
else if ( action[0] == '>' )
result = a > b;
else if ( strcmp ( action, "and" ) == 0 )
result = a && b;
else if ( strcmp ( action, "or" ) == 0 )
result = a || b;
else
die ( "Invalid format" );
stack[top++] = result;
}
int is_valid ( const char *action, size_t offset, size_t limit )
{
size_t i;
for ( i = offset; i < limit + offset; i++ ) {
if ( strcmp ( action, actions[i] ) == 0 )
return 1;
}
return 0;
}
void die ( const char *msg )
{
fprintf ( stderr, "%s\n", msg );
exit ( EXIT_FAILURE );
}This gives rise to a powerful, if somewhat cryptic (at first), notation. For example, to calculate : 7 - 4 7 4 - . 3 ok ( 7 - 4 ) * 5 7 4 - 5 * . 15 ok 7 4 - ok 5 * ok . 15 ok |
|
|
|
|
|
#6 |
|
Programmer
|
hehe, when I look at these codes I just think of how much I like pythons simple commands... phew
Beeg |
|
|
|
|
|
#7 |
|
Professional Programmer
Join Date: Nov 2004
Posts: 250
Rep Power: 4
![]() |
>when I look at these codes I just think of how much I like pythons simple commands...
Well, that is the point of high level languages. The compiler/interpreter does most of the tedious work for you so that you can focus on solving new problems rather than old ones. Of course, for this new power you give up a certain amount of control and flexibility. Writing a clone in Python of the program I gave isn't as short and sweet as you might think. To get the same functionality you still need to work a bit. ![]() |
|
|
|
|
|
#8 |
|
Programming Guru
![]() Join Date: Oct 2004
Location: namespace std
Posts: 1,246
Rep Power: 5
![]() |
i wrote these beginner programs for a four-function calculator awhile back and then a professional programmer wrote a much more complex, yet much more functional solution to the problem. interesting to look at the code. oh, and a good project for beginners because you can incorporate OOP into this type of program so you can practice with classes and functions and hell, you could go buck-wild with pointers and references and arrays and what not. anyway, if you're just starting out, a simple calculator is a good project. (i have given up on the python calculator, i have too much to study with C and C++) now i'm searching for a good test of my now-intermediate C-style skills...any suggestions?
__________________
i put on my robe and wizard hat... Have you ever heard of Plato, Aristotle, Socrates?...Morons. |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|