Can someone tell me why the variable percent = 0? It should be 33.3333 right? (2/6)
because when I run the function below, the result are
Total lines = 6
Odd lines = 2
Percent odd lines = 0
bool count_odd_lines(string a, string b)
{
ifstream in;
ofstream out;
in.open(a.c_str());
out.open(b.c_str());
string s;
int count = 0;
int odd = 0;
if (in && out)
{
while (getline(in, s))
{
count++;
if (s.length() % 2 != 0) odd++;
}
out << "Total lines = " << count << endl;
out << "Odd lines = " << odd << endl;
double percent = odd/count;
out << "Percent odd lines = " << setprecision(4) << percent <<endl;
return true;
}
else return false;
in.close();
out.close();
}
There are two issues:
oddandcountare integer, soodd/countperforms integer (that is, truncating) division.33.33rather than0.3333) you need to multiply the result by100.You can fix both issues like so:
The multiplication does the scaling and also turns the subsequent division into a floating-point one.