苦苦挣扎,似乎无法让它发挥作用。这是我需要做的:
1.询问用户今年的美化季节是多少个星期。
2.动态创建一个双浮点数据数组,可用于存储本赛季每周的销售额。
3.使用for循环,让用户输入本赛季的销售数据。
4.将数组(及其大小)传递给一个函数,该函数将在一个漂亮的表中显示周内的所有销售。
5.拨打另一个函数,将数组作为参数,并将总计季节的销售额(将总数返回到主函数)。
6.该程序告诉用户本赛季的总销售额和每周的平均销售额。
7.删除分配的内存后,将指针设置为0。
任何帮助总是让我不太了解函数或指针。而且我已经读了很多!!
#include <iostream>
#include <iomanip>
using namespace std;
int Weeks = 0;
double total;
double sales;
void SalesTable(int);
double Total (int, double[]);
double average;
int main()
{
double Season[Weeks];
cout << "How many weeks were in the landscaping season this year: ";
cin >> Weeks;
for (int i = 1; i<Weeks+1; i++)
{
cout << "Enter sales data for week " << i <<": ";
cin >> sales;
}
Season[Weeks]=sales;
SalesTable(Weeks);
Total(Weeks, Season);
average = total/Weeks;
cout << "The total sales for the season are: "<<setprecision(2)<<showpoint<<fixed<<total<< endl;
cout << "The average weekly sales were: "<<setprecision(2)<<showpoint<<fixed<<average;
return 0;
}
void SalesTable(int Weeks)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << sales <<endl;
}
}
double Total(int Weeks, double Season[])
{
for(int i = 1; i<Weeks+1; i++)
{
total += Season[Weeks];
}
return total;
}
答案 0 :(得分:1)
好的,使用指针加倍它会做你需要的:
int Weeks = 0;
double total;
double sales;
void SalesTable(int, double*);
double Total (int, double*);
double average;
int main ()
{
double *Season;
cout << "How many weeks were in the landscaping season this year: ";
cin >> Weeks;
Season = new double [ Weeks ];
for (int i = 1; i<Weeks+1; i++)
{
cout << "Enter sales data for week " << i <<": ";
cin >> sales;
Season[i-1]=sales;
}
SalesTable(Weeks, Season);
Total(Weeks, Season);
average = total/(double)Weeks;
cout << "The total sales for the season are: "<<showpoint<<fixed<<total<<endl;
cout << "The average weekly sales were: "<<showpoint<<fixed<<average;
delete[] Season;
return 0;
}
void SalesTable(int Weeks,double *Season)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << Season[i-1]<<endl;
}
}
double Total(int Weeks, double *Season)
{
for(int i = 1; i<Weeks+1; i++)
{
total += Season[i-1];
}
return total;
}
答案 1 :(得分:0)
由于我无法发表评论,我将发布一个新答案:
T-D提供的代码仍然无法正常工作:每个销售周的打印输出总是相同的,因为它不能访问Seasons数组内的元素。
void SalesTable(int Weeks)
{
for(int i = 1; i<Weeks+1; i++)
{
cout << "Sales for week "<< i <<":" << Season[i - 1] << endl;
}
}
另外,要动态创建一个允许用户在运行时控制数组大小的数组,请使用以下代码:
double *season = new double[Weeks];
由于您动态创建了数组,因此必须手动释放其资源:
delete[] season;