2007北京市小学生程序设计友谊赛详细答案

第1题

解法一:在cmath或math.h中,有个round()函数,可以实现四舍五入。

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

int main()
{
	int a;
	cin >> a;
	cout << round(a * 2.54) << endl; 

    return 0;
}

注意:网络上有些人说round()不是四舍五入,而是四舍六入五成双,即round(5.5) = 6, round(6.5) = 6。
我通过在Dev C++, Codeblocks和g++测试,发现C中的round()就是四舍五入,而不是四舍六入五成双。
测试代码为:

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

int main()
{
	float a = 0.5;
	while(a < 100)
	{
		cout << a << ',' << round(a) << endl;
		a += 1.0;
	}

    return 0;
}

解法二:不使用round()函数

#include <iostream>
using namespace std;

int main()
{
	int inch;
	cin >> inch;
	float cm = inch * 2.54;
	cout << int(cm + 0.5) ;

    return 0;
}

第2题

#include <iostream>
using namespace std; 

struct rabbit
{
	string name;	// 名字 
	int len;		// 长度 
	int time;		// 时间 
	float v;		// 速度 
};
 
int main() 
{
	int n; 
	cin >> n;
	float maxV = 0;
	string winner;
	
	rabbit r[n];
	for(int i = 0; i < n; i++)
	{
		cin >> r[i].name >> r[i].len >> r[i].time;
		r[i].v = (float)r[i].len / r[i].time;
		if(r[i].v > maxV)
		{
			maxV = r[i].v;
			winner = r[i].name;
		}
	} 
	
	cout << winner << endl;
	return 0;
}

第3题

#include <iostream>
using namespace std; 

void bubbleSort(int a[], int n)
{
	for(int i = 0; i < n - 1; i++)
	{
		for(int j = 0; j < n - 1 - i; j++)
		{
			if(a[j] > a[j+1])
			{
				swap(a[j], a[j + 1]);
			}
		}
	}
}
 
int main() 
{
	int n; 
	cin >> n;
	int h[n];
	// 这道题用了冒泡排序,下标建议为0~n-1 
	for(int i = 0; i < n; i++)
	{
		cin >> h[i];
	}
	
	bubbleSort(h, n);
	
	int height;
	cin >> height;
	int begin, end;
	for(int i = 0; i < n; i++)
	{
		if(h[i - 1] != height && h[i] == height)
		{
			begin = i;
		}
		
		// 注意,这个if不能改为else if,为什么? 
		if(h[i] == height && h[i + 1] != height)
		{
			end = i;
		}
	}
	
	// 下标记得+1 
	cout << begin + 1 << ' ' << end + 1<< endl;
	
	return 0;
}

咨询信奥课或加微信群,请加微信307591841或QQ307591841
公众号.jpg

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值