问题是询问员工编号1到10 (他们给了我要输入到数组中的数组数字),通过将3个月组合在一起,给出了每个员工的总销售额。在我的加法函数中,它做了correctly....for第一部分的所有事情……它完美地显示了数组中的数字,但是当它添加数组并在这里和那里抛出一个元素时,会导致错误的总数。在我的代码中,我补充说,它应该计算在第一组数字之后相加的数组数字,它不跟在数组后面,这是代码:
我遵循了你们向我展示的内容(顺便说一句),我现在将1号员工的总数加到其余部分中,这是我不想做的。我想输入员工#1的停止显示,然后从3个月数组中的3个数字中添加员工#2的总数停止显示(继续,直到每件显示1~10)我已经输入了我的新代码进行修改。我是C++编程的新手,我还没有学习过类,所以老实说我不能使用它们。
#include <iostream>
#include <iomanip>
#include <cstdlib>
using namespace std;
void displaySales(int sales[10][3]);
void displayTotalSales(int total[10][3]);
int main ()
{
//declare array Jan Feb Mar
int employ[10][3] = {{2400, 3500, 2000},
{1500, 7000, 1000},
{600, 450, 2100},
{790, 240, 500},
{1000, 1000, 1000},
{6300, 7000, 8000},
{1300, 450, 700},
{2700, 5500, 6000},
{4700, 4800, 4900},
{1200, 1300, 400}};
//displays the sales for the month
displaySales(employ);
displayTotalSales(employ);
system("pause");
return 0;
}
//******Functions*******
void displaySales(int sales[10][3])
{
for(int emp = 0; emp < 10; emp++)
{
cout << "Employee # " << emp + 1
<< ": " << endl;
for (int month = 0; month < 3; month++)
{
cout << " Month " << month + 1
<< ": ";
cout << sales[emp][month] << endl;
} //end for
} //end for
} //end function
void displayTotalSales(int total[10][3])
{
int employ = 1; //employee number
int totalSales = 0; // total sales for the employee
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 3; j++)
{
totalSales += total[i][j];
cout << "Employee # " << employ << ": " << endl;
cout << endl;
cout << "Total sales for the month: " << "$" << total[i][j];
cout << endl;
}
cout << " Total Sales for the three months is: $" << totalSales << endl;
cout << endl;
employ++;
}
}发布于 2010-12-13 04:57:38
do {
...
totalSales = (total[i][j] + total[i][j+1] + total[i][j+2]);
j++;
} while (j < 3);J在第一次迭代后越界。
但说真的,使用classes!并使用containers!
哦,你的花括号完全乱了。
发布于 2010-12-13 05:25:02
首先,请更好地组织您的代码!缩进会让这件事变得更容易理解和帮助。
我有一种强烈的感觉,这是一个编程类的家庭作业问题,但我会试着帮助你解决它。
基本上,您的问题是运行在数组的末尾,因为当j == 2时,例如当您使用语句时:
totalSales = (total[i][j] + total[i][j+1] + total[i][j+2]); 您尝试引用的j+2实际上是数组的第5个元素,但该元素并不存在。
我对你的addFunk进行了10秒的重写(请更好地命名函数)
您可以尝试如下所示:
void addFunk(int total[10][3])
{
int employ = 1; //employee number
int totalSales = 0; // total sales for the employee
for (int i = 0; i < 10; i++)
{
for ( int j = 0; j < 3; j ++)
{
totalSales += total[i][j];
}
cout << "employee num " << employ << "earned "
<< "$" << totalSales << endl;
totalSales = 0;
employ++;
totalSales = 0;
}
}发布于 2010-12-13 09:34:27
我可能不适合添加这个答案,但由于没有办法让新手发表评论,我就在这里说。
我同意karl关于学习对象的观点。当我们在大学里学习c和c++时,我们从结构开始,然后转到课堂上,如果你对编程很认真,学习这些东西真的很重要。
类只是描述现实世界中对象的一种方式。它有属性和行为。例如,您可以有一个employee类,它可以存储他们每月的所有收入,并且它内部可以有一个函数,允许您计算他们最近的收入。这些对代码的小补充将使代码更易于阅读、组织和重用。
我强烈建议您花几个小时谷歌一下面向对象的概念,并尝试一些c++示例。它们非常简单。
https://stackoverflow.com/questions/4423930
复制相似问题