Home‎ > ‎Assignments‎ > ‎Hour of Code‎ > ‎Solutions‎ > ‎

Solution | Fractured Fractions

Programming Assignment

Fractured Fractions

Solution

 Program:

// Solution to the "Fractured Fractions" assignment 
// Author: Adina Weisel
// Date: February 12, 2017
#include <iostream>
using namespace std;

class frac {     // making a class called frac
public:
char readafraction();
void printafraction();
float convert();
private:
int num;
int denom;
};

int main()
{
cout << "This program will have fun with fractions that you input. When you \n want to stop, input -1 for both the numerator and the denominator.\n\n";
frac x;     // x is the object of the frac class (read this outloud-we are now going to form a cult ;)
//int numerator, denomenator;
while (x.readafraction() == 'N') {  // if function readafraction returns 'N', do the loop. This means that it is NOT the end of data
cout << "Your fraction is ";
x.printafraction();
cout << "\nIt is equal to ";
cout << x.convert();
cout << endl << endl;
}
return 0;
}

char frac::readafraction() {
cout << "Numerator? ";
cin >> num;
cout << "Denominator? ";
cin >> denom;
if (num == -1)
return 'Y';
else return 'N';
}

void frac::printafraction() {
cout << num << "/" << denom;
}

float frac::convert() {
return double (num) / denom;
}

Console output:

Comments