有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

输出简单java递增不清晰

我正在努力理解Java中递增的基础知识。。。这里我有一个基本的例子,我不太清楚它的输出。。。所以它从4开始,当然是2*2,9是4*4+1,但现在怎么会变成16呢?多谢各位

public class Mystery 
{
public static void main( String[] args )
{
  int y;
  int x = 2;
  int total = 0;


  while ( x <= 10 ) 
  {
     y = x * x;     
     System.out.println( y );   
     total += y;              
     ++x;                        
  } 

  System.out.printf( "Total is %d\n", total );
 } // end main
 } // end class Mystery

输出

  4
  9
 16
 25
 36
 49
 64
 81
 100
 Total is 384

共 (3) 个答案

  1. # 1 楼答案

    16是4*4,这是可以预料的。你的算法先打印2*2,然后打印3*3,而不是4*4+1,顺便说一句,也就是17

  2. # 2 楼答案

    您正在打印这一行的结果:

    y = x * x; 
    

    在每次迭代中x增加1。这是基本乘法:

    2 * 2 = 4
    3 * 3 = 9
    4 * 4 = 16
    5 * 5 = 25
    ...
    

    而且4 * 4 + 1是17而不是9

  3. # 3 楼答案

    x在每次迭代中递增

      x    x*x    total
              
      2    2*2=4    4
      3    3*3=9    13
      4    4*4=16   29
      ...
    

    如果添加更多调试输出,这将非常容易理解:

      while ( x <= 10 ) 
      {
         y = x * x;       
         total += y;
    
         System.out.printf("x=%d    y=x*x=%d   total=%d, x, y, total );
    
         ++x;                        
      } 
    

    enter image description here