注册 登录
编程论坛 C语言论坛

PTA 龟兔赛跑问题

小夏虫 发布于 2019-08-20 13:55, 2913 次点击
7-22 龟兔赛跑 (20 分)
乌龟与兔子进行赛跑,跑场是一个矩型跑道,跑道边可以随地进行休息。乌龟每分钟可以前进3米,兔子每分钟前进9米;兔子嫌乌龟跑得慢,觉得肯定能跑赢乌龟,于是,每跑10分钟回头看一下乌龟,若发现自己超过乌龟,就在路边休息,每次休息30分钟,否则继续跑10分钟;而乌龟非常努力,一直跑,不休息。假定乌龟与兔子在同一起点同一时刻开始起跑,请问T分钟后乌龟和兔子谁跑得快?

输入格式:
输入在一行中给出比赛时间T(分钟)。

输出格式:
在一行中输出比赛的结果:乌龟赢输出@_@,兔子赢输出^_^,平局则输出-_-;后跟1空格,再输出胜利者跑完的距离。

输入样例:
242
输出样例:
@_@ 726

请问我这个代码为什么答案错误了。。。
#include<iostream>
using namespace std;
int main()
{
    int minute=0;
    int rab=0;
    int tot=0;
    int time;
    cin>>time;
    while(minute<=time)
    {
        minute++;
        rab+=9;
        tot+=3;
        if(minute%10==0)
        {
            if(rab>tot)
            {
                minute+=30;
                tot+=90;
            }
        }
    }
    if(tot>rab) cout<<"@_@"<<" "<<tot;
    else if(tot<rab) cout<<"^_^"<<" "<<rab;
    else cout<<"-_-";
}
7 回复
#2
rjsp2019-08-20 14:34
为什么不肯贴链接?
在网上搜了一下,没找到原题。
虽然很怀疑“-_-”那里有问题,但没完整题目要求,不好确认。
#3
小夏虫2019-08-20 16:54
回复 2楼 rjsp
链接啊 不好意思 我贴出来
https://
#4
小夏虫2019-08-20 16:56
回复 2楼 rjsp
我的问题是输出的乌龟行走的路程不正确。
#5
小夏虫2019-08-20 17:55
现在还有两个问题,附上我修改好的代码
#include<iostream>
using namespace std;
int main()
{
    int minute=0;
    int rab=0;//rab为兔子走的路程 tot为乌龟走的路程。
    int tot=0;
    int time;
    cin>>time;//输入总的时间
    while(minute<time)
    {
        minute++;
        rab+=9;
        tot+=3;//每次增加一分钟,兔子走9米 乌龟走3米。
        if(minute%10==0)//如果分钟增加到10的倍数
        {
            if(rab>tot)//判断此时乌龟和兔子走的路程谁大,如果兔子在前面,那么兔子会休息30分钟。
            {
                int count=0;//count代表兔子睡觉的时间,30分钟后兔子就会醒来
                while(minute<time&&count<30)//当现在的时间还没到比赛结束的时间,并且兔子还在睡觉
                {
                    tot+=3;//乌龟继续走
                    minute++;//时间继续增加
                    count++;//兔子睡觉的时间也增加
                }
            }
        }
    }
    if(tot>rab) cout<<"@_@"<<" "<<tot;
    else if(tot<rab) cout<<"^_^"<<" "<<rab;
    else cout<<"-_-";
}
上我刚才发的PTA网站上提交一下发现还有两个点没过。求指教!
#6
H_M2019-08-20 18:13
回复 5楼 小夏虫
网上有,https://blog.
感觉思路与想考你的不同,好的程序简单清晰。
#7
小夏虫2019-08-20 23:09
回复 6楼 H_M
好了 对了
#8
rjsp2019-08-21 09:26
逻辑错误比较多,比如
    while(minute<=time) 一共循环 time+1 次?
    if(minute%10==0) 也就是 minute==0、==10、==20 时触发?
    tot+=90; 你确保剩余时间一定有30分钟可以让乌龟跑?
等等。

另外,这是个非常简单的数学题,90分钟270米后两者状态又恢复到当初,故而有代码
程序代码:
#include <iostream>
#include <algorithm>
using namespace std;

int main( void )
{
    unsigned T;
    cin >> T;

    // 乌龟:每分钟3米
   
// 兔子:每分钟9米。[跑10分钟,息30分钟,跑10分钟,息30分钟,跑10分钟]……
    unsigned tortoise = T*3;
    unsigned hare = T/90*270 + T%90/40*90 + min(T%90%40,10u)*9;

    if( tortoise > hare )
        cout << "@_@ " << tortoise << '\n';
    else if( tortoise < hare )
        cout << "^_^ " << hare << '\n';
    else
        cout << "-_- " << hare << '\n';
}

1