2016-09-23 112 views
0
// Binomial Expansions 
     String the_x, the_y; 
     System.out.println("Binomial Expansions:"); 
     for(int i=0; i<=max; i++){ 
      num = 1; 
      r = i+1; 
      xpow=i; 
      ypow=0; 
      System.out.print("(x + y)^"+i+" = "); 
      if(i==0) System.out.print("1"); 
      for(int j=0; j<=i; j++){ 
       if(j>0){ 
       num = num*(r-j)/j; 
       System.out.print("x^"+(xpow+1)+" + "); 
       System.out.print(num+"x^"+xpow+"y^"+ypow); 
       } 
       xpow--; 
       ypow++; 
      } 
      System.out.println(); 
     } // End of binomial expansions 

我对我的代码有几个问题。java没有打印任何东西0

  1. 如何不打印0和1?并且有什么推荐的方法可以在其功率为0或1时摆脱^

  2. 我打印x两次的原因是,我想x位于在y之前,像这样(x + y)^5 = x^5 + 5x^4y + 10x^3y^2 + 10x^2y^3 + 5xy^4 + y^5但是,如果我不X打印了两次,我的结果看起来像这样(x + y)^5 = x^5 + 5y^1x^4 + 10y^2x^3 + 10y^3x^2 + 5y^4x^1 + 1y^5。我能做什么?

  3. 我认为我的标题和标签不合适,我有什么样的麻烦,我可以稍后搜索?

我看了有什么DecimalFormatTypeCast,但我不认为这两个是不适用这种情况。在此先感谢

+4

我可能会误解你的问题,但为什么不使用if语句来检查0或1,对于这种情况下,有不同的印刷线? – TheFooBarWay

+0

我也这么想过。我很好奇还有其他方法可以做到这一点。 #2对我来说是个大问题 – jaykodeveloper

回答

1

试试这个。

static String power(String v, int p) { 
    switch (p) { 
    case 0: return "1"; 
    case 1: return v; 
    default: return v + "^" + p; 
    } 
} 

static String mult(int k, String... terms) { 
    if (k == 0) 
     return "0"; 
    String r = "" + k; 
    for (String t : terms) { 
     if (t.equals("0")) 
      return "0"; 
     else if (t.equals("1")) 
      continue; 
     else if (r.equals("1")) 
      r = t; 
     else 
      r += t; 
    } 
    return r; 
} 

static void biominal(int max) { 
    System.out.println("Binomial Expansions:"); 
    for (int i = 0; i <= max; i++) { 
     int num = 1; 
     int r = i + 1; 
     System.out.print("(x + y)^" + i + " = "); 
     System.out.print(power("x", i)); 
     for (int j = 1; j <= i; j++) { 
      num = num * (r - j)/j; 
      System.out.print(" + " + mult(num, power("x", i - j), power("y", j))); 
     } 
     System.out.println(); 
    } 
} 

biominal(5); 

结果:

Binomial Expansions: 
(x + y)^0 = 1 
(x + y)^1 = x + y 
(x + y)^2 = x^2 + 2xy + y^2 
(x + y)^3 = x^3 + 3x^2y + 3xy^2 + y^3 
(x + y)^4 = x^4 + 4x^3y + 6x^2y^2 + 4xy^3 + y^4 
(x + y)^5 = x^5 + 5x^4y + 10x^3y^2 + 10x^2y^3 + 5xy^4 + y^5