[英]The operator > is undefined for the argument type(s) java.util.Random, java.util.Random
[英]Assigning a random number to it's respected place with java.util.random 1000 times
我正在嘗試將數字1-10分配給兩個變量。 如果數字大於max,則使用該數字更新max;如果數字小於min,則使用min更新。 始終用生成的任何數量更新總數。 我以為我有它的正確性,但是每當它產生時。 然后最后我必須平均。 這個數字不是隨機的,並且卡在相同的幾個數字上。 不知道我錯了。
package java_programming;
import java.util.Random;
public class Jp{
public static void main(String[] args){
//The Power Operation
double power = Math.pow(5.0,3.0);
//The Square Root Operation
double root = Math.sqrt(12.0);
//The Max Operation
double Maxi = Math.max(23.4, 23.5);
//The Min Operation
double Mini = Math.min(23.4, 23.5);
//The Random Opeartion
double rand = Math.random();
System.out.println("Results");
System.out.println("Math.pow = " + power);
System.out.println("Math.sqrt = " + root);
System.out.println("Math.max = " + Maxi);
System.out.println("Math.min = " + Mini);
System.out.println("Math.random = " + rand);
Jp rs = new Jp();
System.out.println("Min value");
rs.randomStudy();
}
public void randomStudy(){
int total = 0;
int max = -1;
int min = 11;
int iterations = 1000;
Random ran = new Random();
for(int i = 0; i < iterations; i++){
int count = ran.nextInt(10);
min = Math.min(count, min);
max = Math.max(count, max);
total += count;
}
System.out.println("Result of max: " + max);
System.out.println("Result of min: " + min);
System.out.println("Average: " + (1.0 * total / iterations));
}
}
只看randomStudy()
:
public void randomStudy()
{
int total = 0;
int max = -1;
int min = 11;
int i = 0;
Random ran = new Random();
while (i < 1001)
{
for(int count = 1; count<=10;count++)
count = ran.nextInt(11);
if(total < min)
min = total;
if(total>max)
max = total;
System.out.println("Result of max: " + max);
System.out.println("Result of min: " + min);
double average = total/1000;
System.out.println("Average: " + average);
i++;
}
}
更新方法:
public void randomStudy()
{
int total = 0;
int max = -1;
int min = 11;
int iterations = 1000;
Random ran = new Random();
for(int i = 0; i < iterations; i++)
{
int count = ran.nextInt(11);
min = Math.min(count, min);
max = Math.max(count, max);
total += count;
}
System.out.println("Result of max: " + max);
System.out.println("Result of min: " + min);
System.out.println("Average: " + (1.0 * total / iterations));
}
與問題編輯:
[...]
while(i < 1001)
{
for(int j = 0; j < 1000; j++)
[...]
這將循環1000 * 1000(1000000)次,這可能比您嘗試執行的操作還要多
要獲得[ ran.nextInt(10) + 1
]而不是[ ran.nextInt(10) + 1
]的隨機數,請使用ran.nextInt(10) + 1
( 我如何在Java中生成特定范圍內的隨機整數? )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.