一个关于二维数组的问题,编译的时候没有出错,但是在运行的时候输入第三组数值时VC报错。

christianozhao 2008-03-21 01:41:29
下面是我的程序,统计3年中一本书每年的总销量(每个月的销量由人工输入),每一年的销量统计完成后打印出结果,最后显示三年的总销量,在我输入第三年五月份的销量的时候VC报错,程序崩溃了,我也不知道程序出了什么问题,谢谢大家帮助啦!

# include <iostream>

const int MONTHS=12;
const char *months[MONTHS]={"January","Febuary","March","April","May",
"June","July","August","September","October","November","December"};

int main()
{
using namespace std;
int i=1;
int j=1;
double sum=0.0;
int sales[3][MONTHS];
int month;
while(j<=3)
{
cout<<"Enter the "<<j<<" year monthly sales for\"C++ for Fools\":\n";
for(month=0;month<MONTHS;month++)
{
cout<<"Sales for "<<months[month]<<":";
cin>>sales[i][month];
}
double total=0.0;
for(month=0;month<MONTHS;month++)
total+=sales[i][month];
cout<<"Total sales:"<<total<<endl;
i++;
j++;
sum+=total;
}
cout<<"The 3 year's totol sales is:"<<sum<<endl;
return 0;
}

...全文
78 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
Mnky 2008-03-21
  • 打赏
  • 举报
回复
你i和j如果要从1变到3,那么sales生命的时候应该变成 int sales[4][MONTHS];
否则,就把 i,j 初始化为0,循环时用 while(j<3)
hjessica 2008-03-21
  • 打赏
  • 举报
回复

# include <iostream>

const int MONTHS=12;
const char *months[MONTHS]={"January","Febuary","March","April","May",
"June","July","August","September","October","November","December"};

int main()
{
using namespace std;
int j=0;
double sum=0.0;
int sales[3][MONTHS];
int month;
while(j <3)
{

cout <<"Enter the " <<j <<" year monthly sales for\"C++ for Fools\":\n";
for(month=0;month <MONTHS;month++) {
cout <<"Sales for " <<months[month] <<":";
cin>>sales[j][month];
}
double total=0.0;
for(month=0;month <MONTHS;month++)
total+=sales[j][month];
cout <<"Total sales:" <<total <<endl;
j++;
sum+=total;
}
cout <<"The 3 year's totol sales is:" <<sum <<endl;
return 0;
}
christianozhao 2008-03-21
  • 打赏
  • 举报
回复
谢谢楼上的各位。。
没想到犯这么低级的错误。。
基础不够牢固啊!谢谢!
xax100000 2008-03-21
  • 打赏
  • 举报
回复
数组下标。
以后碰到这种问题,自己检查检查。
christianozhao 2008-03-21
  • 打赏
  • 举报
回复
谢谢!我试一下!
ouyh12345 2008-03-21
  • 打赏
  • 举报
回复
total+=sales[i][month];
这里数组的下标应该是从0开始的
ouyh12345 2008-03-21
  • 打赏
  • 举报
回复
跟踪一下,看在哪崩的,然后看看变量是什么值

64,676

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧