2013-06-04 170 views
0

这已经有一段时间了(去年的Java类)。自从我的学校没有提供它以来,一直试图自己学习C++。我写了一个简单的程序来测试我到目前为止学到的东西 - 真正的语法 - 在我进入中间件之前。无论如何,我只想强调我从来没有找到答案,我宁愿你问我关于我的后勤问题,以便我可以重新思考问题,并可能自行完成。我认为,因为我可以在Java中成功编写这个代码,所有代码在C++中都会很好,但是我遇到了可变的问题。我试图调试和步入,但我仍然不明白为什么我的一些变量没有得到我分配的值。如果你能指出我正确的方向,我会非常感激。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); 

} 
+0

请列举这导致问题的变量,你期待什么样的价值他们有什么价值观,他们实际上拥有。 – Philipp

+0

尝试阅读std :: vector或http://isocpp.org/tour。 C++不是Java,因为您从实验中看到 –

+0

make int team [0]; - > int团队[100];一个用户只能输入一个小于100的数字,平均值应该是总数/队伍数量。然后你在得分输出中有硬编码队伍[0] – sethi

回答

2

在线路

int team[0]; 

要创建与0的条目的阵列。 C++中的数组不能增加或缩小。为了解决这个问题,无论是分配你知道后动态需要多大的空间阵列:

int * team = new int[teamCount]; 

(不要忘记调用delete[] team;当你不需要它了,或者内存空间还没有回收)

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

你的下一个错误是在这里:

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

您在每次循环迭代过程中一次又一次地输出第一队的价值。

顺便说一句:这两种错误是刚刚在Java作为错误:)

+0

这是一种战术性的战术还是在我的解释中出现了问题? – Philipp

+0

(我不知道什么是downvote。)你的解释很棒。每个人都提醒说矢量不是动态的。这似乎是我的问题的开始。而且我昨天才知道“垃圾”,所以谢谢你提醒我,所以我可以在我的代码中实现它! – Addy75

+0

downvote在'vector'之前提到'new []'(或者更确切地说,提到'new []')。 – Griwes

3

您的团队阵列没有与其关联的存储空间。在C++中数组不是动态的,请尝试使用矢量来代替,并调整其大小,当你阅读teamCount

+2

嗯,'int team [0];'实际上是零'int's long。 'team'是一个独特的,非'NULL'指针,但取消引用它是UB。 –

+0

团队[0]不是一个整数。 –

+0

正确。将编辑 –

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] 
} 
6

你的阵列

int team[0]; 

将不是在C工作++。顺便说一句,你不能分配0大小的数组这样
尝试C++容器代替

std::vector<int> team; 
+0

是的,它会:http://stackoverflow.com/questions/1087042/c-new-int0-will-it-allocate-memory –

+0

@AndrewW:不,它不会,你的链接不提供证据它确实。 –

+0

@AndrewW不,它不是,至少不是问题中所显示的方式。 – juanchopanza