U569334 金正恩将军的C++难题 题解

· · 休闲·娱乐

U569334 金正恩将军的C++难题

为了照顾一些没有学过结构体的同学,我使用了一种不用结构体的方法。

1.非结构体法(由题解制作人编写)

//U569334 金正恩将军的C++难题
//版权:©heyangfd 
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>

using namespace std;
void vansei()
{
    int n;//输入数据组数n 
    scanf("%d",&n); 
    string s,s1;//s代表输入时的地名,s1则代表占比最大的地名 
    int a,b,maxn=0;//a是会C++的人数,b是总人数,maxn记会C++人数地区的最大值 
    int sum=0,sum1=0;//sum表示会C++的总人数,sum1表示总人数 
    for(int i=1;i<=n;i++)//循环输入数据、处理数据 
    {
        cin>>s>>a>>b;//首先输入 
        sum+=a;//递增会C++的元素 
        sum1+=b;//递增地区总人数 
        if(a>maxn)//找出会C++人数最多的地区 
        {
            maxn=a;//更新最大值变量 
            s1=s;//更新地区名称 
        }
    }
    double x=sum*1.0/sum1*100.0;//计算出总的百分比 
    char s2='%';//字符百分号在格式化输出时需要单独定义 
    printf("%d  %.2lf%c  ",sum,x,s2);//输出数字 
    cout<<s1;//输出字符串 
}
int main()
{
    vansei();//运行 
    return 0;
}

结构体法

//U569334 金正恩将军的C++难题
//版权:©Tanhaoyue2011 
#include<iostream>
#include<string>
#include<cstdio>

using namespace std;

struct Korea//定义一个结构体 
{
    string place;//这个字符串用于存储地名 
    int learnt, all;//learnt存储会C++的人数,all则表示总人数 
};
const int N = 1e4 + 5;//定义常量,便于定义数组(本题输入数据非常少,这一步可省) 
Korea man[N];//定义结构体数组 
int n,cnt,tot,maxn,l;//n存储数据的数量;cnt统计会C++各地区的总人数;tot表示全部地区的总人数;maxn存储和更新最大值;l表示会C++人数最多地区在数组中的位置。 
int main(){
    cin >> n;//输入数据数量 
    for(int i = 1; i <= n; i++){//循环输入,处理数据 
        cin >> man[i].place;//输入地名 
        cin >> man[i].learnt >> man[i].all;//输入会C++的人数和总人数 
        cnt += man[i].learnt;//统计会C++的总人数 
        tot += man[i].all;//统计全部地区的总人数 
        if(man[i].learnt >= maxn) l = i;//找到最大值在数组中的位置 
    }
    cout << cnt << "  ";//输出各个地区会C++ 的总人数 
    printf("%.2lf", ((cnt * 1.0) / (tot * 1.0) * 100.0));//计算并输出会C++的人数占总人数的百分比 
    cout << "%" << "  ";//输出百分号 
    cout << man[l].place << endl;//输出会C++人数最多的地区名称 
    return 0;//结束 
}

Enjoy