算法概论第二周作业2.2: 随机生成一个n bit位的长整数。

来源:互联网 发布:为什么说网络三大邪书 编辑:程序博客网 时间:2024/05/16 06:12
import java.util.Scanner;  
    
public class RndInteger {  
    public RndInteger(){  
        System.out.println("请输入一个指定二进制数的位数");  
        Scanner scan = new Scanner(System.in);  
        try{  
            int input = scan.nextInt();  
            System.out.println("随机生成的"+input+"二进制数转化long整数是");  
            System.out.println(createRndInteger(input));  
        }catch(Exception e){  
            System.out.println("输入错误,请重新输入正确的数");  
            RndInteger num = new RndInteger();  
        }  
      
    }  
  
    public long createRndInteger(int n){  
        
        long result  = (long)(Math.random()*Math.pow(2,n-1)+Math.pow(2,n-1));  
        return result;  
    }  


    public static void main(String args[]){  
    RndInteger num = new RndInteger();  
    }  



0 0