一道C语言编程比赛题(时钟追赶问题)
问题描述:
大概的意思是:任意给一个角度,求出时钟上的秒分时指针之间的角度大于等于这个角度的概率。
解决的方案如下:
/************************************************************************* > 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除以总秒数。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。