假设我有一些跳水比赛的参与者,并由裁判评分。我需要根据参与者的姓名显示总分。
我该如何解决这个问题?
int scores[5][2], i, j;
int sum =0;
for(i=0;i<5;i++)
{
char name [50];
cout << "Enter participant's name: ";
cin >> name;
cout<<"Enter scores for " << name <<endl;
for(j=0;j<2;j++)
{
cin>>scores[i][j];
}
}
sum = 0;
for(i=0; i<5; i++)
{
char name [50];
sum = 0;
for(j=0; j<2; j++)
{
sum += scores[i][j];
}
cout<<"Total scores of Participant " << name << " " <<" is "<<sum<<endl;
}
return 0;
}
3条答案
按热度按时间iyr7buue1#
首先,这是我在这里的第一个答案(有史以来),所以我非常兴奋,希望它能有所帮助!=)
当你写“
char name[50]
”时,你实际上是做了一个字符数组(单个字母的数组),循环中的每个循环都写在同一个数组上(每次只写名字的第一个字母)。我想你的意思是创建一个名称(字符串)数组,你也可以用
char name[5][50]
来做,但使用库字符串更容易。我认为一个更好的实现方式是:我希望这对你有帮助,如果你有任何问题,我会尽我所能回答!Good luck =)
u91tlkcl2#
变量有两种主要类型,global 和 local。
全局变量
这些类型的变量可以被子作用域访问,也可以被函数访问(如果它在全局命名空间中)。
局部变量
这些类型的变量被限制在单个作用域中,但可以由子作用域访问。大多数情况下,如果只有一个作用域拥有一个变量,则该变量被称为“局部”变量。
“全局”和“局部”与我的问题有什么关系?
如果我们看一下这段代码
变量
name
是该for
循环的局部变量。这意味着它不能在该循环之外访问。在另一个for
循环中,再次声明name
变量。这两个变量是两个独立的变量。一旦变量超出作用域,其数据将被销毁(假设变量是堆栈分配的)。这意味着您没有办法从第一个name
变量获取名称信息。如何解决这个问题?
将
name
变量标记为该范围中的 global 变量,现在,第二个
for
循环可以访问带有所需相关数据的name
变量。注意:如果没有理由严格使用原始字符串数组(
char name[50]
),假设名称可以超过50个字符,请使用std::string
。ajsxfq5m3#
你可以像这样定义一个新的struct:
它包含一个名字(如果有的话,超过49个字符),并拥有两张选票。
这是一个如上所述的五个struct的数组。
简单地访问运动员I姓名及其得分: