How do you use math.random to generate random ints?

后端 未结 7 883
情话喂你
情话喂你 2020-12-06 01:23

How do you use Math.random to generate random ints?

My code is:

int abc= (Math.random()*100);
System.out.println(abc);

All it print

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-06 01:35

    int abc= (Math.random()*100);//  wrong 
    

    you wil get below error message

    Exception in thread "main" java.lang.Error: Unresolved compilation problem: Type mismatch: cannot convert from double to int

    int abc= (int) (Math.random()*100);// add "(int)" data type
    

    ,known as type casting

    if the true result is

    int abc= (int) (Math.random()*1)=0.027475
    

    Then you will get output as "0" because it is a integer data type.

    int abc= (int) (Math.random()*100)=0.02745
    

    output:2 because (100*0.02745=2.7456...etc)

提交回复
热议问题