首页 > 试题广场 >

找x

[编程题]找x
  • 热度指数:21842 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
输入一个数n,然后输入n个数值各不相同,再输入一个值x,输出这个值在这个数组中的下标(从0开始,若不在数组中则输出-1)。

输入描述:
测试数据有多组,输入n(1<=n<=200),接着输入n个数,然后输入x。


输出描述:
对于每组输入,请输出结果。
示例1

输入

2
1 3
0

输出

-1
import java.util.Scanner;
public class Main {
    public static void main(String [] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int n = sc.nextInt();
            if(n <1 || n> 200){
                continue;
            }
            int [] num = new int [n];
            for(int i = 0; i <num.length; i ++){
                num [i] = sc.nextInt();
            }
            int x = sc.nextInt();
            int j = 0;
            for(; j <num.length; j ++){
                if(x == num [j]){
                    System.out.print(j);
                    break;
                }
            }
            if(j == num.length){
                System.out.print(“ - 1”);
            }
        }
    }
}
发表于 2018-08-02 22:13:26 回复(0)