我正在尝试开发一个程序来计算到2100年的海平面。根据研究我发现海平面将是2.5英尺(30英寸) - 6.5英尺(这是78英寸)。我的程序要求用户输入他们想要计算海平面上升多少英寸的年份,但我希望每年的信息是.3488和.9069英寸之间的随机数,因为这些是每年的平均值。海平面2.5英尺和6.5英尺。所以我的问题是如何为用户输入的每年生成随机数,这样我就可以计算出海平面上升了多少,然后以加仑数输出。
/takes the input from the user of all the way up to which year
/they want to know the number of inches/ gallons the sea level has risen
/using reiman summs and a chart
/
/
/*******************************************************************************/
import java.util.Random;
import java.util.Scanner;
public class CalcProject
{
public static void main(String[] args)
{
//variables for the program
int year;
int numOfYears;
double leastRise = .3488; //y = .3488x , x is the inches of rainfall
double highRise = .9069; //y= .9069x , x is the inches of rainfall
double seaLevel1;
double seaLevel2;
//Describing what the program does to the user
System.out.println("This program caluclates the number of gallons / inches" +
"the sea level will rise based on your input." + "\n");
//Asking for the users year they want to calculate
System.out.println("Please enter which year you wish to know how much the water level will have risen since 2014");
Scanner scan = new Scanner(System.in);
year = scan.nextInt();
if(year <= 2014 || year > 2100)
{
do
{
System.out.println("Please enter a valid year between 2015 and 2100");
year = scan.nextInt();
} while((year <= 2014 || year > 2100));
}
//puts the year into a number of years from 2014
numOfYears = year-2014;
System.out.println("The number of years between now and the year you chose is: " + numOfYears);
//uses the least inches of sealevel
seaLevel1 = numOfYears * leastRise;
System.out.println("The total sealevel in inches is " + seaLevel1 + " for " + year);
//uses the most inches of seaLevel
seaLevel2 = numOfYears * highRise;
System.out.println("The total sealevel in inches is " + seaLevel2 + " for " + year);
//calculating radnom numbers for each year
答案 0 :(得分:0)
这是一种处理奇怪随机数的简单方法。
int numOfYears;
double leastRise = .3488;
double highRise = .9069;
double seaLevel3 = 0;
int i = 0;
while (i < numOfYears) {
double rand = Math.random();
if (rand >= leastRise && rand <= highRise) {
// rand is some sea level value representing a year
seaLevel3 += rand;
i++;
}
}
System.out.println("The total sealevel in inches is " + seaLevel3 + " for " + year);