补充C++语句: 补充按照//后面的提示补充语句
发布网友
发布时间:2022-05-22 13:00
我来回答
共2个回答
热心网友
时间:2024-03-10 05:43
#include <iostream>
#include <iomanip>
using namespace std;
int main( )
{
float *monthSales;
float total = 0;
float average;
int numOfSales;
int count;
cout << setiosflags(ios::fixed)<< setprecision(2);
cout << "How many monthly sales will be processed? ";
cin >> numOfSales;
// Fill in the code to allocate memory for the array pointed to by monthSales.
monthSales = new float[numOfSales];//分配内存,用new分配numOfSales个元素空间
if ( // 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) )
{//他大意好像是说了如果你的指导员告诉你的编译器不需要就去掉这部分,我的建议是去掉这部分,就是整个if,包括里面的cout和return这部分代码,因为原来的C语言的时代,如果内存用malloc分配失败会返回NULL指针,可以用if判断,但是c++标准如果new分配失败是不会返回NULL指针的,而是抛出一个badalloc的异常,所以if没任何意义,try才有意义,但是没给出try,干脆整个去掉这部分
cout << "Error allocating memory!\n";
return 1;
}
cout << "Enter the sales below\n";
for (count = 0; count < numOfSales; count++)
{
cout << "Sales for Month number "
<< count + 1//输出第一个要输入的月份的月份号,当然也可以不加1,从0开始,个人以为加1更符合一般习惯,就是输入第一个月份的数额 Fill in code to show the number of the month
<< ":";
// Fill in code to bring sales into an element of the array
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;
// Fill in the code to deallocate memory assigned to the array.
delete monthSales;//对于简单类型的动态数组不一定非要delete[]
return 0;
}
热心网友
时间:2024-03-10 05:44
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float *monthSales;
float total = 0;
float average;
int numOfSales;
int count;
cout << "How many monthly sales will be processed? ";
cin >> numOfSales;
// Fill in the code to allocate memory for the array pointed to by monthSales.
monthSales = new float[ numOfSales ];
if ( numOfSales < 1 || monthSales == NULL )
{
cout << "Error allocating memory!\n";
return 1;
}
cout << "Enter the sales below\n";
for ( count = 0; count < numOfSales; count++ )
{
cout << "Sales for Month number "
<< count + 1 // Fill in code to show the number of the month
<< ":";
// Fill in code to bring sales into an element of the array
cin >> monthSales[ count ];
}
for ( count = 0; count < numOfSales; count++ )
{
total = total + monthSales[count];
}
average = total / count;// 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.
return 0;
}