c++ - how to make cin >> numOfSales to take only intege? I don\'t want decimal p
ID: 662370 • Letter: C
Question
c++ - how to make cin >> numOfSales to take only intege? I don't want decimal points
----------------------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float *monthSales; // a pointer used to point to an array
// holding monthly sales
float total = 0; // total of all sales
float average; // average of monthly sales
int numOfSales; // number of sales to be processed
int count; // loop counter
cout << fixed << showpoint << setprecision(2);
cout << "How many monthly sales will be processed? ";
cin >> numOfSales;
while (cin.fail()) //Error handling if input is not an integer
{
cout << " Invaild input.Try Again. How many monthly sales will be processed? ";
cin.clear();
cin.ignore(256, ' ');
cin >> numOfSales;
}
monthSales = new float[numOfSales]; // Fill in the code to allocate memory for the array pointed to by
// monthSales.
if (numOfSales <= 0// Fill in the condition to determine if memory has been
// allocated (or eliminate this if construct if your instructor
// tells you it is not needed for your compiler)
)
{
cout << "Error allocating memory! ";
return 1;
}
cout << "Enter the sales below ";
for (count = 0; count < numOfSales; count++)
{
cout << "Sales for Month number "
<< count + 1 // Fill in code to show the number of the month
<< ": ";
cin >> monthSales[count]; // Fill in code to bring sales into an element of the array
while (cin.fail() || monthSales[count]<0)
{
cout << " Invaild input.Try Again. Sales for Month number "
<< count + 1 // Fill in code to show the number of the month
<< ": ";
cin.clear();
cin.ignore(256, ' ');
cin >> monthSales[count];
}
}
for (count = 0; count < numOfSales; count++)
{
total = total + monthSales[count];
}
average = total / numOfSales;// Fill in code to find the average
cout << "Average Monthly sale is $" << average << endl;
delete[] monthSales; // Fill in the code to deallocate memory assigned to the array.
system("pause");
return 0;
}
Explanation / Answer
monthSales = new float[numOfSales] statement is wrong since, monthSales is float.
what you need to do , is to typecast numsales and all calculations involved it to int.
or at the end only do the typecasting.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.