一道C语言编程比赛题(时钟追赶问题)

问题描述:

The three hands of the clock are rotating every second and meeting each other many times everyday. Finally, they get bored of this and each of them would like to stay away from the other two. A hand is happy if it is at least D degrees from any of the rest. You are to calculate how much time in a day that all the hands are happy.

大概的意思是:任意给一个角度,求出时钟上的秒分时指针之间的角度大于等于这个角度的概率。

解决的方案如下:

/*************************************************************************
	> File Name: clock.c
	> Author: Baniel Gao
	> Mail: [email protected] 
	> Blog: blog.csdn.net/createchance 
	> Created Time: Tue 08 Apr 2014 05:23:27 PM CST
 ************************************************************************/
#include <stdio.h>

#define HALF_DAY	43200
#define SEC_RATE	6
#define MIN_RATE	(1.0/10)
#define HOUR_RATE	(1.0/120)

void happy_times(double degrees);
static inline double fabs(double val);
static inline double degree_of_circle(double degree);

int main(void)
{
	double degrees;

	printf("Please input a degree: ");
	scanf("%lf", °rees);
	if (degrees > 120 || degrees < 0) {
		printf("The degree must be a number between 0 and 120! \n");
		return -1;
	}
	happy_times(degrees);

	return 0;
}

void happy_times(double degrees)
{
	int sec = 0;
	double gaps[3];
	int happy_times = 0;

	while (sec <= HALF_DAY) {
		if (fabs((SEC_RATE * sec) % 360 - degree_of_circle(MIN_RATE * sec)) <= 180)
			gaps[0] = fabs((SEC_RATE * sec) % 360 - degree_of_circle(MIN_RATE * sec));
		else
			gaps[0] = 360 - fabs((SEC_RATE * sec) % 360 - degree_of_circle(MIN_RATE * sec));

		if (fabs(degree_of_circle(MIN_RATE * sec) - HOUR_RATE * sec) <= 180)
			gaps[1] = fabs(degree_of_circle(MIN_RATE * sec) - HOUR_RATE * sec);
		else
			gaps[1] = 360 - fabs(degree_of_circle(MIN_RATE * sec) - HOUR_RATE * sec);

		if (fabs((SEC_RATE * sec) % 360 - HOUR_RATE * sec) <= 180)
			gaps[2] = fabs((SEC_RATE * sec) % 360 - HOUR_RATE * sec);
		else
			gaps[2] = 360 - fabs((SEC_RATE * sec) % 360 - HOUR_RATE * sec);

		if (gaps[0] >= degrees && gaps[1] >= degrees && gaps[2] >= degrees)
			happy_times++;
		sec++;
	}
	printf("Happy times: %%%.3f \n", happy_times * 100.0 / (sec - 1));
}

static inline double fabs(double val)
{
	if (val > 0.0)
		return val;
	else
		return (0 - val);
}

static inline double degree_of_circle(double degree)
{
	if (degree < 360.0)
		return degree;
	else
		return (degree - (int)(degree / 360.0) * 360);
}

解决的大致思路如下:

定义一个秒的变量,用来从0自增到43200(12小时,因为每12小时三个指针合并一次),判断每次是否符合问题描述的happy times,符合的话happy times加1,否则不操作。最后用happy times除以总秒数。

你可能感兴趣的:(C语言)