// classes.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h> //required for fflush()
class math //declare math class, with 2 data members and 3 member functions
{
public:
int num1; //num1 and num2 are members of the math class
int num2;
int addition(math* pointer)
{
return pointer->num1 + pointer->num2; //returns sum of num1 and num2
}
int subtraction(math* pointer) //returns difference of num1 and num2
{
return pointer->num1 - pointer->num2;
}
int multiplication(math* pointer) //returns product of num1 and num2
{
int ans = 0;
for (int i=1; i<= pointer->num2; i++) //adds num1 to itself for num2 amount of times
ans += pointer->num1;
return ans;
}
int division(math* pointer, int& k) //returns quotient of num1 and num2
{
int quotient;
while (pointer->num1 >= pointer->num2) //loops as long as dividend >= divisor
{
++quotient; //increments quotient by 1 each time the divisor is subtracted from dividend
pointer->num2 -= pointer->num1; //at the end of the while loop, dividend becomes remainder.
}
k = pointer->num2;
return quotient;
}
};
void getnumbers (int& i, int& j, int choice) //scans in values for num1 and num2
{
char* opname[]={"added", "subtracted", "mulitplied", "divided"}; //determines phrasing of second sentence
printf ("Please enter a number: \n");
fflush(stdin); //flushes out previous inputs
scanf ("%d", &i);
printf ( "Please enter another number to be %s: \n", opname[choice]);
scanf ("%d", &j);
}
int _tmain(int argc, TCHAR *argv[], TCHAR *envp[])
{
math operation;
math* pointer = &operation; //pointer to address of operation, object of math class
int& i = operation.num1; //these references will be arguments to the hmm function
int& j = operation.num2; //and will be modified accordingly
printf ("\nWelcome to my calculator. Select a number below: \n");
printf ("0: Addition\n");
printf ("1: Subtraction\n");
printf ("2: Multiplication\n");
printf ("3: Division\n");
int choice;
fflush(stdin); //flushes out previous inputs
scanf ("%d", &choice);
getnumbers(i, j, choice);
//prints answer according to choice
if (choice == 0)
printf ("Answer: %d\n\n", operation.addition(pointer));
if (choice == 1)
printf ("Answer: %d\n\n", operation.subtraction(pointer));
if (choice == 2)
printf ("Answer: %d\n\n", operation.multiplication(pointer));
if (choice == 3)
int remainder;
int& k = remainder;
printf ("Quotient: %d\n", operation.division(pointer, k));
printf ("Remainder: %d\n\n", remainder);
return 0;
}
EDIT:
i just shifted
int remainder;
int& k = remainder;
to right above main
and it compiles fine now!
this is mysterious!
anyway, while my code compiles fine,
it does not display the quotient and remainder as i desired.
ideas? the division function -- while awkward -- was meant to test my knowledge of while loops. it works, as i extracted it from another function, before i embarked on using classes.

New Topic/Question
Reply




MultiQuote




|