I've been reading about constructors and classes, unfortunately I've never been able to read and comprehend very well, it would help greatly if I could have some feedback on constructors and the like.
I am making a Fraction Calculator, which is basically going to accept two different fractions # / # and # / #, and it's going to reduce the fractions to decimals so they're easier to work with, and then it's going to compare these fractions (By divding them, adding them, multiplying them, and subtracting them)
It's basically going to be a program that's similiar to this: http://www.dreamincode.net/code/snip...tm#lastComment
I've been reading over that code since I started this project, and I've got an okay handle on how to work things, but a little input would be nice as well. Here's my code to date:
Expand|Select|Wrap|Line Numbers
- // Written by Michael C. Dillon
- #include <iostream>
- #include <string>
- #include <cstdlib>
- #include <stdlib.h>
- #include <sstream>
- #include <stdio.h>
- using namespace std;
- class rational
- {
- int num;
- int den;
- void simplify();
- public:
- rational();
- rational(int,int);
- };
- rational::rational()
- {
- num=0;
- den=1;
- }
- rational::rational(int n, int d)
- {
- int i = n/d;
- }
- void rational::simplify()
- {
- float n=(float)this->num;
- float d=(float)this->den;
- int i = 2;
- while ((i<=n) && (n!=1))
- {
- while ((n/i==(int)n/i) && (d/i == (int)d/i))
- {
- n/=i;
- d/=i;
- }
- i++;
- }
- num = n;
- den=(n==0)? 1:d;
- }
- int GetIntVal(string strConvert) {
- int intReturn;
- intReturn = atoi(strConvert.c_str());
- return(intReturn);
- }
- int main ()
- {
- string first,f2,f1;
- size_t pos;
- size_t space;
- while (true)
- {
- cout << "Enter your first fraction (0 to exit): ";
- getline(cin,first,'\n'); // Enter first fraction
- if (first=="0") //Exit function
- {
- break;
- }
- else
- {
- pos = first.find('/'); // Searches for the '/'
- f2 = first.substr(pos+1);
- f1 = first.substr (0,pos);
- space = first.find_first_of("\ "); // Searches for a space
- if (pos!=string::npos) //If it contains a /, indicating a proper fraction
- {
- if (space!=string::npos) // If there are spaces
- {
- f1.replace(space,space,""); // Remove them
- f2.replace(space,space,""); // Remove them
- }
- int num = GetIntVal(f1); // Conversion to Int
- int den = GetIntVal(f2); // Conversion to Int
- double percent = double(num)/den; //Cast that Int!
- cout << "pos = " << pos + 1 << "\nnum = " << num << "\nden = " << den << "\nThe rational decimal of this fraction is: " << percent << "\n";
- }
- else
- {
- cout << "Correct formatting: ##/##\n"; // Just incase. ^-^
- }
- }
- }
- return EXIT_SUCCESS;
- }