I wrote the code below, but CAN NOT figure out why the percentages aren\'t being
ID: 648043 • Letter: I
Question
I wrote the code below, but CAN NOT figure out why the percentages aren't being displayed. Can anyone help?!
#include
#include
#include
#include
using namespace std;
int main()
{
string INPUT_FILE_NAME = "numbers.txt";
ifstream input_file;
int positive_numbers = 0,
negative_numbers = 0,
zero_numbers = 0,
count = 0,
value;
double percent_positive,
percent_negative,
percent_zero;
// open input file
input_file.open(INPUT_FILE_NAME);
if (!input_file.fail())
{
while (input_file >> value)
{
if (value > 0)
positive_numbers++;
else if (value < 0)
negative_numbers++;
else
zero_numbers++;
count++;
}
// calculate percentages
percent_positive = (positive_numbers / count) * 100;
percent_negative = (negative_numbers / count) * 100;
percent_zero = (zero_numbers / count) * 100;
//display percentages
cout << fixed << setprecision(2);
cout << "There were " << percent_negative << "% negative numbers." << endl;
cout << "There were " << percent_zero << "% numbers equal to zero." << endl;
cout << "There were " << percent_positive << "% numbers greater than zero." << endl;
// close input file
input_file.close();
}
else
{
cout << "Error, unable to open input file " << INPUT_FILE_NAME << "." << endl;
}
return 0;
}
Explanation / Answer
#include<iostream.h>
#include<fstream.h>
using namespace std;
int main()
{
string INPUT_FILE_NAME = "numbers.txt";
ifstream input_file;
int positive_numbers = 0,negative_numbers = 0,pcount = 0,ncount=0,zerocount=0,value;
double percent_positive,percent_negative;
// open input file
input_file.open(INPUT_FILE_NAME);
if (input_file!=NULL)
{
while (input_file >> value)
{
if (value > 0)
{
cout<<"positive percentages are";
positive_numbers+=value;
pcount++;
}
else
if (value < 0)
{
cout <<"negative numbers are";
negative_numbers+=value;
ncount++;
}
else
zerocount++;
}
// calculate percentages
percent_positive = (positive_numbers / pcount) * 100;
percent_negative = (negative_numbers / ncount) * 100;
//display percentages
cout << fixed << setprecision(2);
cout << "There were " << percent_positive <<endl;
cout << "There were " << percent_negative<< endl;
cout << "There were " <<zerocount << endl;
// close input file
input_file.close();
}
else
{
cout << "Error, unable to open input file " << INPUT_FILE_NAME << "." << endl;
}
return 0;
}
// These are some modifications we have to do to display percentages