java Java中如何生成正数和负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12973358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:00:52  来源:igfitidea点击:

how to generate positive and negative numbers in Java

javamathrandom

提问by Reshad

Possible Duplicate:
How to generate random positive and negative numbers in java

可能的重复:
如何在java中生成随机正负数

Hello I am trying to create a method in Java to create negative and positive values in Java.

您好,我正在尝试在 Java 中创建一种方法来在 Java 中创建负值和正值。

the problem is that I don't know how to get this programmed but I do know the logic.. here is what I tought it should be

问题是我不知道如何编程,但我知道逻辑..这就是我认为应该是的

 Random generator = new Random();

 for (int i = 0; i < 21; i++)
 {
       System.out.print(generator.nextInt(100) + 1);
       System.out.println();
 } 

but with the code above I get only positive values and I need values between -100 and 100 but how can I accomplish something like that?

但是使用上面的代码,我只得到正值,我需要 -100 到 100 之间的值,但是我怎样才能完成这样的事情?

回答by Pablo Santa Cruz

You can use:

您可以使用:

Random generator = new Random();
int val = 100 - generator.nextInt(201);

Or, as JoachimSauer suggested in the comments:

或者,正如 JoachimSauer 在评论中所建议的那样:

int val = generator.nextInt(201) - 100;

回答by Peter Lawrey

The general formula is

一般公式是

int val = rand.nextInt(max - min + 1) + min;

Note that minand maxcan be negative. (max > min)

请注意,minandmax可以是负数。(最大值 > 最小值)