在多个for循环和数组中打印名称
printing name in multiple for loops and arrays
我遇到了一个小问题,如何打印获胜候选人的姓名?请参阅此处的说明,输入五个名字、他们的票数和得票率,谁得票最多谁获胜。我不知道我的代码做得对不对,但它有效。。除了名字部分。我已经尝试了从很多for循环到转移数组之类的一切。我几乎完成了代码。
这是代码
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char candidates[50];
int votes[5]={0};
float percent[5]={0};
int a,b,c,d,e,i;
int maxx;
int champ=0;
char winner[50];
cout << "Enter the candidates' last names: ";
cout << endl;
for(a=1;a<=5;a++)
{
cout << a << ". ";
cin >> candidates;
}
cout << endl;
cout << "Enter their number of votes: " << endl;
for(b=1;b<=5;b++)
{
cout << b << ". ";
cin >> votes[b];
}
cout << endl;
cout << "percentage of votes: " << endl;
for(c=1;c<=5;c++)
{
cout << c << ". ";
percent[c]=votes[c]*0.2;
printf("%.2fn", percent[c]);
}
cout <<"CandidatesttVotestt% of Votes" << endl;
for(int k=1;k<=5;k++)
{
cout << candidates[k] << "ttt" << votes[k] << "ttt";
printf("%.2fn", percent[k]);
}
maxx=percent[0];
for(d=1;d<=5;d++)
{
if(maxx<percent[d]);
{
//what happens here?
}
}
return 0;
}
您应该保留一个2d字符数组或字符串数组来存储候选名称,而不是一个1d数组。
char candidates[5][10]; //
for(int i = 0; i < 5; i++)
{
cin >> candidates[i];
}
然后保留一个变量来存储获胜候选的索引
int winIndex = 0;
int winPercent = 0;
for(int i = 0; i < 5; i++)
{
if(percent[i] > winPercent)
{
winPercent = percent;
winIndex = i;
}
}
最后打印获胜候选人的姓名;cout<lt;候选者[winIndex];
在面向对象的方法中,您可以创建一个具有以下信息的类
class Candidate
{
string name;
int votes;
float percent;
};
使用string candidates[50];
而不是char candidates[50];
则cin >> candidates[a];
相关文章:
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 在一定长度后从数组中打印时缺少整数
- 数组元素打印的递归方法
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 打印矢量数组中的所有元素
- 打印问题.我在数组中打印值时遇到一些问题
- 数组类 阵列的打印输出
- 动态分配的聊天数组打印缺失的数据和空
- 如何打印 2D 字符数组C++
- 如何修改代码以打印出数组 v2
- 在C++中初始化和打印 2D 数组
- 将浮点数转换为无符号字符数组并打印出来
- C++ 打印包含数据结构的数组
- 如何让字符数组在一行而不是多行中打印出来?
- 打印字符数组地址的正确方法
- 按字母顺序打印存储在字符数组中的信息
- 使用递归反转和打印出数组的内容
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 如何在运行时在对象数组中动态追加新对象C++并打印它们
- 加载有空指针的字符数组的打印值