I'm working on an exercise from a book(C++ without fear) as follows:
Write a program that uses the Fraction class by setting a series of
values by calling the “set” function: 2/2, 4/8, -9/-9, 10/50, 100/25. Have the program print out the results and verify that each fraction was correctly simplified.
This is the best way I could think to do it, but I'm getting errors I don't know how to handle like "error: name look up of 'i' changed for new ISO 'for' scoping"
Any help would be nice, and maybe something to explain why I got these errors.
#include <iostream>
#include <string>
usingnamespace std;
class Fraction {
private:
int num, den; // Numerator and denominator.
public:
void set(int n, int d)
{num = n; den = d; normalize();}
int get_num() {return num;}
int get_den() {return den;}
private:
void normalize(); // Convert to standard form.
int gcf(int a, int b); // Greatest Common Factor.
int lcm(int a, int b); // Lowest Common Denom.
};
int main() {
int a, b;
string str;
Fraction fract;
Fraction fc[5];
while (true) {
for (int i=0;i<=4;i++){
cout << "Enter numerator: ";
cin >> a;
cout << "Enter denominator: ";
cin >> b;
fc[i] = fract.set(a,b);
}
}
cout << "Your fractions are: \n";
for(int i=0;i<=AV;i++){
cout << fc(i) << endl;
}
cout << "Do again? (Y or N) ";
cin >> str;
if (!(str[0] == 'Y' || str[0] == 'y'))
break;
}
system("PAUSE");
return 0;
}
// ---------------------------------------------------
// FRACTION CLASS FUNCTIONS
// Normalize: put fraction into standard form, unique
// for each mathematically different value.
//
void Fraction::normalize(){
// Handle cases involving 0
if (den == 0 || num == 0) {
num = 0;
den = 1;
}
// Put neg. sign in numerator only.
if (den < 0) {
num *= -1;
den *= -1;
}
// Factor out GCF from numerator and denominator.
int n = gcf(num, den);
num = num / n;
den = den / n;
}
// Greatest Common Factor
//
int Fraction::gcf(int a, int b) {
if (b == 0)
return abs(a);
elsereturn gcf(b, a%b);
}
// Lowest Common Multiple
//
int Fraction::lcm(int a, int b){
int n = gcf(a, b);
return a / n * b;
}
Well, for one thing, line 38 calls "fc(i)", but there is no such function. Do you mean fc[i]? Even then, fc[i] is a Fraction object, which has no << operator, since you didn't define one. Even if you had, it still wouldn't output anything (or just nonsense), because fc[i] is never assigned a value: set() has no return value!
Also, just a minor point: you're using a while() loop, yet instead of controlling it, you're letting it run wild until it hits "break". Why not simply use a boolean to control the condition? Does the same, but much prettier.