现在有一个机器人,可以给它N个指令,每一个指令都是让他往特定一个方向走一个距离,比如“上 100”,再“左 100”,则其最终会到达一个点,求该点到原点的直线距离
第一行为一个整数n,1<=n<=100接下来n行是指令每个指令分为两部分,第一个是方向,共有left,right,up,down四个方向,第二个为行进的距离,为正整数,两个部分用空格分割,整数不会大于10000
输出为最终的点离原点的位置的直线距离,保留2位小数
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; }