实验目的:
掌握一维数组的使用,掌握字符数组的使用,掌握数组做参数的。
题目一:
编写一个程序,允许用户输入在一个当地选举中5位候选人的姓氏和每位候选人得到的票数。然后程序应该输出每一位候选人的姓氏、候选人的得票数和候选人占总票数的百分比。程序还应该输出选举的获胜者。样例输出是:
Candidate Votes Received %of Total Votes
John 5000 25.91
Miller 4000 20.72
Duffy 6000 31.09
Robinson 2500 12.95
Ashtony 1800 9.33
Total 19300
The Winner of the Election is Duffy
编写程序:
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
void input(string str[], int votes[], int *total, int *max)
{
*total = 0;
*max =0;
cout << "Please Enter the Five Candidates' Last name" << endl;
for(int i = 0; i<5; ++i)
{
cin>>str[i]>>votes[i];
if(i != 0 && votes[*max] < votes[i] ) *max = i;
*total += votes[i];
}
}
void output(string str[], int votes[], int *total,int *max)
{
cout<<"Candidate Votes Received % of Total Votes "<<endl;
for(int i = 0; i<5; ++i)
{
cout<<str[i]<<" "<<votes[i]<<" "<<setiosflags(ios::fixed)<<setprecision(2)<<100*votes[i]*1.0/(*total)<<endl;
}
cout<<"Total "<<*total<<endl<<endl;
cout<<"The Winner of the Election is "<<str[*max]<<"."<<endl;
}
int main ()
{
//返回0
string lastName[5];
int votes[5];
double per[5];
int total;
int max;
input(lastName,votes,&total,&max);
output(lastName,votes,&total,&max);
return 0;
}