我想创建一个c ++程序,可以计算3年内售出的数量。
我想用2维数组和for循环(练习题的要求)
来做但不知怎的,我无法得到我想要的结果。计算和存储之间存在一些误差。你能帮我辨认一下这个错误吗?
#include <iostream>
#include <string>
#include <array>
using namespace std;
int main(){
int quantity[3][12];
int sum[3];
int *p;
p=sum;
int total;
int year=0;
string months[12]={
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"Octorber",
"November",
"December"
};
for (int i=0; i<12; i++) {
cout<<"Enter the quantity sold in "<<months[i]<<endl;
cin>>quantity[year][i];
if(i==11&&year<3){
year++;
i=-1;
}
}
year=0;
for (int i=0; i<12; i++) {
sum[year]+=quantity[year][i];
if (i==11&&year<3) {
i=(-1);
year++;
}
}
year=0;
for (int i=0; i<3; i++) {
cout<<"the information for year "<<(i+1)<<" is " <<endl;
for (int i1=0; i1<12; i1++) {
cout<<quantity[year][i1]<<endl;
}
cout<<"the sum of the "<< (i+1)<< " year: "<<sum[year]<<endl;
total+=sum[year];
}
cout<<"the total amount sold in three year is "<<total<<endl;
return 0;
}
答案 0 :(得分:0)
问题出在本节:
year=0;
for (int i=0; i<3; i++) {
cout<<"the information for year "<<(i+1)<<" is " <<endl;
for (int i1=0; i1<12; i1++) {
cout<<quantity[year][i1]<<endl;
}
cout<<"the sum of the "<< (i+1)<< " year: "<<sum[year]<<endl;
total+=sum[year];
}
cout<<"the total amount sold in three year is "<<total<<endl;
return 0;
}
看起来你认为你正在迭代一年,而你实际上正在迭代i和i1。为什么不使用你使用的相同技巧而不是i1 for loop?
if (i==11&&year<3) {
i=(-1);
year++;
}