C语言算法题:两只老鼠打洞相遇问题
C语言算法题:两只老鼠打洞相遇问题
问题描述
有一堵墙,两只老鼠从两边向中间打洞。
- 大老鼠第一天打洞一尺,之后每天的打洞进度是前一天的一倍。
- 小老鼠第一天打洞一尺,之后每天的进度是前一天的一半。
计算并输出它们几天可以相逢,以及相逢时各自打了多少尺。
输入格式
输入1 个整数,代表墙的厚度,单位为尺
输出格式
- 第一行输出1 个整数,表示相遇时所需的天数
- 第二行输出2 个浮点数,分别为小鼠和大鼠打洞的距离,单位为尺,保留小数点后1 位数字。
Python代码示例
wall = int(input()) #墙壁的厚度
rat, mouse, day, time = 1, 1, 0, 1 #大鼠速度、小鼠速度、天数、当天工作时长(1表示工作一整天)
distance_of_rat, distance_of_mouse = 0, 0 #大鼠路程、小鼠路程
while wall > 0:
if wall - mouse - rat < 0:
time = wall / (mouse + rat)
wall = wall - mouse - rat
distance_of_mouse = distance_of_mouse + time * mouse
distance_of_rat = distance_of_rat + time * rat
rat = rat * 2
mouse = mouse / 2
day = day + 1
print(day)
print(round(distance_of_mouse, 1), round(distance_of_rat, 1)) #使用round函数来保留小数点后一位
C语言代码实现
#include<stdio.h>
int main()
{
int wall;
float rat = 1, mouse = 1, time = 1;
float distance_of_rat = 0, distance_of_mouse = 0;
int day = 0;
scanf("%d", &wall);
while (wall > 0)
{
if (wall - mouse - rat < 0)
{
time = wall / (mouse + rat);
}
wall = wall - mouse - rat;
distance_of_mouse = distance_of_mouse + time * mouse;
distance_of_rat = distance_of_rat + time * rat;
rat = rat * 2;
mouse = mouse / 2;
day = day + 1;
}
printf("%d\n", day);
printf("%.1f %.1f\n", distance_of_mouse, distance_of_rat);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/hxh 著作权归作者所有。请勿转载和采集!