In C++ language, I need the output in 2 decimals places in the output. This work
ID: 3723462 • Letter: I
Question
In C++ language, I need the output in 2 decimals places in the output. This works but the 2 decimal places are missing. Are do I place two decimal places in?
void printResults(alphabetCountType letters[], ofstream &out, int counts){
// header in the file
out << "Letter Number Percentage";
cout << counts;
// print the data in the file
for (int i = 0; i < NO_LETTERS_IN_ALPHABET; i++){
out << " " << static_cast<char>(i+65)
<< " " << letters[i].capitalCount
<< setw(9)<< right
<< setprecision(5) << fixed
<< (letters[i].capitalCount *100)/counts << "%";
out << " " << static_cast<char>(i+97)
<< " "<< letters[i].lowerCaseCount
<< setw(9)<< right
<< setprecision(5) << fixed << showpoint
<< (letters[i].lowerCaseCount *100)/counts << "%";
}; // end of for loop
cout << " Printed results to the output file";
} // end of print results function
Explanation / Answer
use
setprecesion(2) << fixed
before printing any varible that you want to print with 2 decimal places
if you want to print everything with 2 decimal places, just declare that once in beginning of function
void printResults(alphabetCountType letters[], ofstream &out, int counts){
// header in the file
out << "Letter Number Percentage";
cout << counts;
cout << setprecision(2) << fixed;
// print the data in the file
for (int i = 0; i < NO_LETTERS_IN_ALPHABET; i++){
out << " " << static_cast<char>(i+65)
<< " " << letters[i].capitalCount
<< setw(9)<< right
<< (letters[i].capitalCount *100)/counts << "%";
out << " " << static_cast<char>(i+97)
<< " "<< letters[i].lowerCaseCount
<< setw(9)<< right << showpoint
<< (letters[i].lowerCaseCount *100)/counts << "%";
}; // end of for loop
cout << " Printed results to the output file";
} // end of print results function