Quantcast
Channel: C++博客-所有随笔
Viewing all articles
Browse latest Browse all 7881

一道模拟题——机器人行走距离计算

$
0
0


    某少年宫引进了一批机器人小车。可以接受预先输入的指令,按指令行动。小车的基本动作很简单,只有3种:左转(记为L),右转(记为R),向前走若干厘米(直接记数字)。

    例如,我们可以对小车输入如下的指令:

    15L10R5LRR10R20

    则,小车先直行15厘米,左转,再走10厘米,再右转,...

    不难看出,对于此指令串,小车又回到了出发地。

    你的任务是:编写程序,由用户输入指令,程序输出每条指令执行后小车位置与指令执行前小车位置的直线距离。

【输入、输出格式要求】

    用户先输入一个整数n(n<100),表示接下来将有n条指令。

    接下来输入n条指令。每条指令只由L、R和数字组成(数字是0~100之间的整数)

    每条指令的长度不超过256个字符。

    程序则输出n行结果。

    每条结果表示小车执行相应的指令前后位置的直线距离。要求四舍五入到小数后2位。

    例如:用户输入:
5
L100R50R10
3LLL5RR4L12
LL
100R
5L5L5L5

    则程序输出:
102.96
9.06
0.00
100.00
0.00

结题思路:
模拟机器人行走即可,用数字表示机器人的方向,向上为0,向右为1,下为2,左为3。设初始状态机器人方向为0,则遇到R就将当前方向加1,遇到L将当前方向减1。x轴向右增大,y轴向上增大。
代码如下:
import java.util.*;

public class Main {
    
static int x = 0;
    
static int y = 0;
    
static int nowdir = 0;
    
static int N;
    
static String instr;
    
public static void main(String[] args)
    
{
        Scanner sc 
= new Scanner(System.in);
        N 
= sc.nextInt();
        sc.nextLine();
        
for(int i = 0; i < N; i++){
            instr 
= sc.nextLine();
            x 
= 0;
            y 
= 0;
            nowdir 
= 0;
            pro();
            
double dis0 = Math.sqrt(x * x + y * y);
            System.out.printf(
"%.2f\n", dis0);
        }

    }

    
static void pro(){
        
boolean isnumbg = false;
        
int numbgp = 0;
        instr 
= instr + "#";
        
for(int i = 0; i < instr.length();){
            
if(Character.isDigit(instr.charAt(i))){
                
if(isnumbg){
                    i
++;
                    
continue;
                }

                
else{
                    numbgp 
= i++;
                    isnumbg 
= true;
                }

            }

            
else{
                
if(isnumbg){
                    isnumbg 
= false;
                    String str1 
= instr.substring(numbgp, i);
                    
int dis = Integer.parseInt(str1);
                    
if(nowdir == 0){
                        y 
+= dis;
                    }

                    
else if(nowdir == 2){
                        y 
-= dis; 
                    }

                    
else if(nowdir  == 1){
                        x 
+= dis;
                    }

                    
else
                        x 
-= dis;
                }

                
else{
                    
char c = instr.charAt(i);
                    
if(c == 'R'){
                        nowdir 
= (nowdir + 1% 4;
                    }

                    
else if(c == 'L'){
                        nowdir 
= (nowdir + 3% 4;
                    }

                    i
++;
                }

            }

        }

    }

}





小鼠标 2013-07-07 17:16 发表评论

Viewing all articles
Browse latest Browse all 7881

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>