题目:
机器人站在笛卡尔坐标系的原点,面向y轴正方向,给定若干指令,求机器人最终位置。
多组测试数据,每组数据第一行为m,表示有m个操作,0 < m < 100。
接下来m行,每行一个指令。
指令格式:
“TURN”:右转90度。
“GO” NUM:直走NUM的距离。
每组数据对应一行输出机器人最终所在的坐标,空格隔开,保留3位小数。
数据保证最终结果可以用double精确表示。3 TURN GO 1 TURN
1.000 0.000
代码:
#include<iostream>
#include<string>//substr()
#include<cstdlib>//atof
#include<iomanip>//fixed
using namespace std;string str;
int direction;//0表示y正,1 x正,2 y负,3 x负
void position(double &, double &, string);//void position(double , double);
int main()
{int n; while (cin >> n){//double x = 0; double y = 0;//double x, y = 0;//int n; cin >> n;direction = 0;double x = 0; double y = 0;cin.ignore(0x7fffffff, 'n');for (int i = 0; i < n; i++){getline(cin, str);//cout << str[i];position(x, y, str);}cout << fixed << setprecision(3) << x << " " << y << endl;}return 0;
}void position(double &x, double &y, string s)
{if (s == "TURN") { direction = (direction + 1) % 4; //(direction + 1) / 4; return;}if (s.substr(0, 2) == "GO"){if (direction == 0) y = y + atof(s.substr(3).c_str());else if (direction == 1) x = x + atof(s.substr(3).c_str());else if (direction == 2) y = y - atof(s.substr(3).c_str());else x = x - atof(s.substr(3).c_str());}
}
本文发布于:2024-02-04 19:04:24,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170714319458616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |