您的位置:首页 > 其它

数组元素在使用前一定要初始化否则运行结果将是不确定的

2013-03-10 14:27 190 查看
/*本程序要求输入3年内每个月的销售额,并逐一输出每一年的销售额,最后计算出三年的总销售额*/

#include<iostream>

int main()

{

 using namespace std;

 const int YEAR=3;

 const int MONTH=12;

 int sales[YEAR][MONTH];

 int sum[YEAR]={0}; //存储每一年的销售额

//一定要初始化,否则结果将是不确定的

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int sum[YEAR];//没有初始化的情况

/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

 int total=0;

 const char * months[]=

 {

  "January",

  "February",

  "March",

  "April",

  "May",

  "June",

  "July",

  "August",

  "Sepetember",

  "October",

  "November",

  "December"

 };

 for(int year=0;year<YEAR;year++)

 {

  cout<<"第"<<year+1<<"年"<<endl;

  for(int month=0;month<MONTH;month++)

  {

   

   cout<<"《C++ For Fools》"<<months[month]<<"'s sales : ";

   cin>>sales[year][month];

   sum[year]+=sales[year][month];//没有初始化时,此时sum[year]的值将是不确定的

  }

  total+=sum[year];

  cout<<"\n第 "<<year+1<<" 年卖了 : "<<sum[year]<<"本."<<endl<<endl<<endl;

 }

 cout<<"\n这"<<YEAR<<"年一共卖了 : "<<total<<"本."<<endl;

 return 0;

}

1.在没有初始化的情况下:



输出的结果将是不确定的

2.初始化后

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐