取一维数组中的数字平均值

时间:2017-09-17 23:10:02

标签: c++ arrays class

我目前正在为我的Prog 2课程进行一项任务,该课程涉及创建一个需要在数组中存储评级的类电影并获取评级的平均值。我已经完成了大部分程序,但我无法弄清楚为什么我的平均值没有正确打印出来,我只是继续得到相同的值。

此外,我不想在“平均观看者评分”之后显示数字,而是想说一句话。例如,平均1为“可怕”,2为“坏”,3为“好”,4为“好”,5为“好”。

我是C ++的新手,所以任何指导都会很精彩。谢谢!

我的班级声明:

class Movie {

private:
    int rate[5];
    int ratings;
    string movie;
    string userRate[5] = {"Terrible","Bad","Okay","Good","Great"};
    string mpaa;

public:
    Movie();
    Movie(string title, string mpaaRating);
    void setMPAA(string mpaaRating);
    double getAverage();
    void addRating(int rating);
    friend ostream& operator << (ostream &out, Movie &M);
};

getAverage()函数:

double Movie::getAverage()
{
    int total = 0;

    for (int i = 0; i < 5; i++)
    {
        total += rate[i] * (i+1);
        ratings++;
    }


    if (ratings > 0)
        return total / ratings;
    else
        return 0;
}

主:

int main() {

    Movie A("Inception","PG-13");
    Movie B("Fear and Loathing in Las Vegas","PG-13");

    A.addRating(1);
    A.addRating(3);
    A.addRating(5);
    A.addRating(5);
    A.addRating(5);

    B.addRating(3);
    B.addRating(2);
    B.addRating(1);
    B.addRating(4);
    B.addRating(5);

    cout << A << endl;
    cout << B << endl;
}

OUTPUT

Movie: Inception
MPAA Rating: PG-13
Avg. Viewer Rating: 3

Movie: Fear and Loathing in Las Vegas
MPAA Rating: PG-13
Avg. Viewer Rating: 3

1 个答案:

答案 0 :(得分:0)

因为您正在执行整数除法。您应该首先将变量转换为浮点数。所以改变:

std::string line ("17,17,\"Jackson & Kolmar\",\"Jackson & Kolmar, Eastbound, Southeast  Corner\",41.87685748,-87.73934698,0,,1");
std::size_t found=0, foundBack; 
int i;
for(i=0;i<3 && found!=std::string::npos;i++){   
    foundBack = found;
    found=line.find(",",found+1);
}

std::cout << line.substr(foundBack+1,found-foundBack-1) << std::endl;

为:

return total / ratings;