用户输入数组元素

问题描述 投票:0回答:2

我有20名球员,每位球员可以投票3次,共20名球员之一。如果第一个输入“数字”是10,我怎样才能将投票添加到userToVote [10] [vote],这是数组中的第10位。

#include <iostream>
#include <string>
using namespace std;

int userToVote[20][3];
int vote,number;

int main()
{
    for(int i = 0;i<20;i++)
    {
        for(int z = 0;z<3;z++)
        {

            cout << "Hello player "<< i << "Insert the id you want to vote and the vote (0 or 1) ";
            cin >> number >> vote;
            cout << userToVote[number][vote];

        }
    }

}
c++
2个回答
0
投票

因为player可以投票3次。你可以在每次投票时增加userToVote[number][vote]。这样,投票就可以增加。你可以像这样改变你的代码。

        cout << "Hello player "<< i << "Insert the id you want to vote and the vote (0 or 1) ";
        cin >> number >> vote;
        userToVote[number][vote]+=1;
        cout << userToVote[number][vote];

0
投票
  • 在这里你不存储(不需要)哪个用户投票给哪一个?
  • 因此,采用二维阵列是浪费空间。只有一维阵列就足够了。
  • 即使你想存储哪个玩家投票特定,你也应该存储我的价值。
  • 所以这个计划的目的似乎是特定玩家有多少票?
  • 你可以用这种方式尝试一维数组。
  • 如果你想存储哪个玩家投票,你需要有20x20阵列。因为在最坏的情况下,每个玩家都可以投票(只有一个)特定的人。基于约束,它可能会增加。

.

#include <iostream>
#include <string>
using namespace std;
int userToVote[20]={0};
int number;
int main()
{
    for(int i = 0;i<20;i++)
    {
        for(int z = 0;z<3;z++)
        {
            cout << "Hello player "<< i << " This is your chance "<<z+1<<" to which player you want to vote?";
            cin >> number;
            cout << userToVote[number]++;
        }
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.