0

已经有一段时间了(去年的 Java 课)。因为我的学校不提供 C++,所以我一直在尝试自己学习 C++。我写了一个简单的程序,只是为了测试我到目前为止所学的东西——实际上只是语法——在我进入中间的东西之前。无论如何,我只想强调我从不寻找答案,我宁愿你问我的后勤问题,这样我就可以重新考虑事情并可能自己完成它。我认为既然我可以用 Java 成功地编写它,那么在 C++ 中一切都会很好,但我遇到了变量问题。我尝试调试并逐步完成,但我仍然不明白为什么我的一些变量没有得到我分配给它们的值。如果您能指出我正确的方向,我将不胜感激。

// This program will create any number of teams the user chooses, 
// give each a score and calculate the average of all the teams.

#include <iostream>
using namespace std;

int main(){

    //number of teams
    int teamCount;
    //array to keep scores
    int team[0];
    //total of scores
    int total=0;
    //average of all scores
    int average=0;

    cout<<"How many teams do you want to keep scores of?"<<endl;

    cin>>teamCount;

    //cout<<teamCount;

    //ask the person for the score as many time
    //as there are teams.
    for(int i=0; i<teamCount; i++){
        cout<< "Give me the score of team "<< i+1<<":"<<endl;
        cin>>team[i];

        total+=team[i];
    }

    average = teamCount/total;

    //output the list of the scores
     for(int i=0; i<teamCount; i++){
         cout<<"Team "<<i+1<<" score is:"<<team[0]<<endl;
     }

    cout<<"and the average of all scores is "<<average<<endl;

    return (0);

} 
4

4 回答 4

6

你的阵列

int team[0];

在 C++ 中不起作用。顺便说一句,您不能以这种方式分配 0 大小的数组
尝试使用 c++ 容器

std::vector<int> team;
于 2013-06-04T14:59:54.327 回答
3

您的团队阵列没有与之关联的存储。在 C++ 中,数组不是动态的,请尝试使用向量,并在读取 teamCount 时调整其大小

于 2013-06-04T14:55:30.400 回答
2

在行

int team[0];

您正在创建一个包含 0 个条目的数组。C++ 中的数组不能增加或缩小。要解决此问题,请在知道数组需要多大后动态分配数组:

int * team = new int[teamCount];

delete[] team;(当你不再需要它时不要忘记调用,否则内存永远不会回收)

或者更好地使用面向对象的方式并使用类std::vector,它是 Java 类 ArrayList 的 C++ 等价物。

你的下一个错误在这里:

//output the list of the scores
 for(int i=0; i<teamCount; i++){
     cout<<"Team "<<i+1<<" score is:"<<team[0]<<endl;
 }

在每次循环迭代期间,您一次又一次地输出第一个团队的价值。

顺便说一句:这两个错误在 Java 中都是错误的 :)

于 2013-06-04T15:00:19.503 回答
1

尝试这个:

average = total / teamCount; //Lets calculate the average correctly. Note: Integer division

//output the list of the scores
 for(int i=0; i<teamCount; i++){
     cout<<"Team "<<i+1<<" score is:"<<team[i]<<endl; //We want each value, not only team[0]
 }
于 2013-06-04T14:59:06.790 回答