我试图将数字1-10分配给两个变量。如果数字大于最大值,则使用该数字更新最大值,如果该数字小于最小值,则使用最小的最新信息。一直以生成任何数字来更新总数。我以为我的正确,但是每当生成时。然后,最后我必须平均它。这个数字不是随机的,并且将其粘在相同的几个数字上。不知道我有什么问题。
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++;
}
}
- 初始化变量:总计,最大,min,i,ran
- 循环1000次
- 循环10次
- 将计数设置为[0,10]
- 检查并设置最小/最大
- 打印最小/最大/平均
- 循环10次
- 可以使用计数器进行一段循环,但通常是使用for liop完成的
- 循环直到获得一个随机数> = 10没什么意义,因为您只想要一个随机数
- min/max可能预计是随机计数的最小/最大值,而不是总数的最低/最大值(并且更清楚地使用Math.min/max)
- 计算平均值应通过双分裂完成,而不是整数除法
- 通常,当打印结果时,人们期望总体结果,而不是在计算的每个阶段
更新的方法:
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)次,这可能比您想做的要多一点
要获取随机数[1,10]而不是[0,10],请改用ran.nextInt(10) + 1
(我如何在Java中的特定范围内生成随机整数?)