0

お久しぶりです(昨年のJavaクラス)。私の学校では提供されていないので、独学で 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

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では同じように間違っています:)

于 2013-06-04T15:00:19.503 に答える