如何在Java中均匀显示一行数字

huangapple go评论66阅读模式
英文:

How to display a line of numbers equally in java

问题

//Static void displaySpace(double start, double end, int count){
// Display numbers between start and end inclusively
// The numbers are spaced equally
// Assume start < end and count is at least 2.
// displaySpace(10,20,3)
// The answer to the question is 10.0 15.0 20.0
while (min < max && count >= 2)
    for (int i = min; i <= max; i++) {
        for (double j = count - 1; j >= 2; j--) {
            System.out.print(j + " ");
        }
        System.out.print(i + " ");
    }
    System.out.println();
}
I keep just getting 10-20 displaying on a loop.
英文:

Im having trouble only displaying the correct numbers, I know how to get the formula is have count-1 have 10/2 = 5 but now I want to count up from the start making it 10 15 20.

//Static void dispalySpace(double start, double end, int count){
// Display numbers between start and end inclusively
//The numbers are spaced equally
//Assume start &lt; end and count is at least 2.
//displaySpace(10,20,3)
//The answer to the question is 10.0 15.0 20.0
while(min&lt;max &amp;&amp; count&gt;=2)
       for(int i=min; i&lt;=max; i++) {
          for(double j = count-1; j&gt;=2; j++) {
             System.out.print(j + &quot; &quot;);
    			}
    			System.out.print(i + &quot; &quot;);
    		}
    	System.out.println();
    }

I keep just getting 10-20 displaying on a loop.

答案1

得分: 1

你首先需要计算步长,即需要向“min”添加多少,以使得最终数量达到“count”。对于第一个输出,你不需要添加任何内容,因此它比“count”少1,即

double step = (max-min) / count - 1;

这就是你需要在循环的每一步中添加的量,从“min”开始,所以

for (double i = 0; i <= max ; i = i + step) {
    System.out.print(i) ;
}
英文:

You first need to calculate the steep size, ie what do you have to add to min so that you end up with count numbers. For the first output, you won't have to add anything, so it's one less than count , ie

double step = (max-min) / count - 1;

That's what you have to add each step of the loop, starting with min , so

for (double i = 0; i &lt;= max ; i = i + step) {
    System.out.print(i) ;
} 

huangapple
  • 本文由 发表于 2020年8月26日 04:53:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63586930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定