首页 > 试题广场 >

机器人指令

[编程题]机器人指令
  • 热度指数:100 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
现在有一个机器人,可以给它N个指令,每一个指令都是让他往特定一个方向走一个距离,比如“上 100”,再“左 100”,则其最终会到达一个点,求该点到原点的直线距离



输入描述:
第一行为一个整数n,1<=n<=100
接下来n行是指令
每个指令分为两部分,第一个是方向,共有left,right,up,down四个方向,第二个为行进的距离,为正整数,两个部分用空格分割,整数不会大于10000


输出描述:
输出为最终的点离原点的位置的直线距离,保留2位小数
示例1

输入

2
up 100
left 100

输出

141.42

说明

如上图所示,距离为100*根号二,取两位小数后为141.42
#include<bits/stdc++.h>
using namespace std;
class kilometer
{
public:
    int x;
    int y;
    kilometer()
    {
        x=0;
        y=0;
    }
    kilometer(int a,int b):x(a),y(b){};
};
int main()
{
    int n;
    cin>>n;
    kilometer temp(0,0);
    for(int i=0;i<n;i++)
    {
        string str;
        int a;
        cin>>str;
        if(str=="right")
        {
            cin>>str;
            a=atoi(str.c_str());
            temp.y+=a;
        }
        else if(str == "left")
        {
            cin>>str;
            a=atoi(str.c_str());
            temp.y-=a;
        }
        else if(str == "up")
        {
            cin>>str;
            a=atoi(str.c_str());
            temp.x+=a;
        }
        else if(str == "down")
        {
            cin>>str;
            a=atoi(str.c_str());
            temp.x-=a;
        }
    }
    double re;
    int x=abs(temp.x-0);
    int y=abs(temp.y-0);
    re=sqrt(x*x+y*y);
    cout <<fixed<< setprecision(2)<< re << endl;
    return 0;
}

发表于 2021-01-08 10:59:53 回复(0)