0

我正在处理关于足球的 C++ 作业,但遇到了地图问题。

我遇到的问题是,当我存储 2 个或更多“中场”作为键时,即使 cout 数据显示不同,但是当我对第二个值进行乘法 -> 第二个值时,它“加起来”第一个 ->第二个值并与之相乘。

例如

John   midfielder   1
Steven midfielder   3

我有一个已经在 playerPosition 中读取的程序。所以地图是这样的:

John 1 (Key, Value)
Steven 3 (Key, Value)

if(playerName == a->first && playerPosition == "midfielder")
{
    cout << a->second*2000 << endl;   //number of goals * $2000
}

所以正确地,程序应该输出:

2000
6000

但相反,我得到

2000
8000

所以,我假设它将 1 加到 3(结果为 4)并乘以 2000,这是完全错误的......

我在程序中尝试了 cout a->first 和 a->second ,我得到:

John 1
Steven 3

但是在乘法之后,就完全不同了。有任何想法吗?

谢谢。


编辑:好的,我试试。我实际上是在计算每个职位字段的奖金。我已经将字段数据插入到地图中,这是实际代码。

multiset<string, less<string> >::iterator q, p = myset.begin();
q = myset.begin()++;

while (p != myset.end())
{        
        if(*p == *q)
        {
            currentScore = (int) myset.count(*p);
            mymap.insert(pair<string, int>(*p, currentScore));
        }
        else if(*p != *q && topScore == 0)
        {
            topScore = (int) myset.count(*q);
            topScorer = *q;
            mymap.insert(pair<string, int>(*q, topScore));
        }
        else if(*p != *q)
        {
            currentScore = (int) myset.count(*p);
            mymap.insert(pair<string, int>(*p, currentScore));

            if(currentScore > topScore)
            {
                topScore = currentScore;
                topScorer = *p;
                mymap.insert(pair<string, int>(*p, topScore));
            }
        }
        p++;
}



map<string, int>::iterator a = mymap.begin();
while(a != mymap.end())
{
if(playerName == a->first && playerPosition == "goalkeeper")
{
   goalkeepers++;
   goalkeeperBonus+=(a->second*5000);
   sumBonus+=goalkeeperBonus;
}
else if(playerName == a->first && playerPosition == "midfielder")
{
   midfielders++;
   midfielderBonus+=(a->second*2000);
   sumBonus+=midfielderBonus;
}
a++;
}

测试数据为:

Score: 3-1 
Ben
Steven
Ben
Score: 2-0 
John
Steven
Score: 1-0 
Ben
Score: 0-0
Score: 1-1 
Cole
Score: 1-2
Ben
Score: 3-0
Cole
Steven
Ben

我试图在 while 循环期间进行 cout,我得到的输出为:

Ben 5
Cole 2
John 1
Steven 3

这应该是史蒂文有 3 个进球的正确输出。但我得到 4,加上约翰的。有没有办法将奖金分配给玩家姓名的 a->first?

4

2 回答 2

2

midfielderBonus+=(a->second*2000);

所以 += 意味着它将累积数据。midfielderBonus=0我假设您在转移到下一个玩家时会忘记 a 。有点难以分辨,因为您包含的代码片段没有显示奖励变量的初始化。

于 2010-05-17T17:21:02.313 回答
0

我在您包含的代码中看不到任何会导致您得到的东西。当然,显然还有更多的事情可以解释它,特别是因为你的 if 似乎应该只适用于一个玩家。

于 2010-05-17T16:07:51.037 回答