2012-07-31 75 views
1

這個for循環應該對樹形圖中包含的所有值進行求和。這是有效的,但在內部循環之後,上下值用於計算精確度。看來這從來沒有被執行過。用Java簡單計算的問題

我在做什麼錯?

  // for each row 
     for (Entry<String, TreeMap<String, Integer>> table_row : table.entrySet()) { 

      // write the label 
      String row = table_row.getKey() + ","; 

      int up = 0; 
      int down = 0; 
      float accu = 0; 
        // for each treemap in the row 
      for (Entry<String, Integer> collumn : table_row.getValue().entrySet()) { 
       row += collumn.getValue() + ","; 
       down += collumn.getValue();//this works 
       if (collumn.getKey() == table_row.getKey()) { 
        up = collumn.getValue(); 
        } 
      } 

    ---------> accu = (up/down) * 100; //this is not executed?? 
      System.out.println("t: " + up + " n: " + down + " a: " + accu); 
      row = row + Float.toString(accu) + " %"; 
      writer.println(row);//this works too but output is always 0% 
     } 
+0

你確定沒有例外嗎? – kosa 2012-07-31 20:31:47

+0

沒有什麼是trowhn – jorrebor 2012-07-31 20:32:17

+0

然後,我想聲明正在執行,但值可能是零 – kosa 2012-07-31 20:33:49

回答

1

整數除法!

down值大於你的up大,向下取整到零,所以每次分配accu時候,你實際上在做這個accu = (0) * 100

如果您正在尋找精度,你應該做上下浮動,而不是或者在分割之前進行演員製作。

3

你可能不希望==在你的比較中,而是用equals()...除非你期待它們是字符串的同一個實例。

+0

向上和向下都是整數,所以我不認爲equals()在那裏工作。 – kosa 2012-07-31 20:34:23

+0

沒有鑰匙與==比較,他們是字符串。 – cjstehno 2012-07-31 20:35:13

+0

注意...這會導致零值。 – cjstehno 2012-07-31 20:35:38

3

我假設你問爲什麼accu總是0在內聯你的意見。
accu = (up/down) * 100;
字面100int以及updown。所以結果可能會變爲0

只需投射到float,這樣您就不會失去精確度。
accu = ((float)up/down) * 100;
這將作爲劇組將先師,自如果一個操作數,如果float另一個也被轉換爲float即使int埃格爾

0

您遇到的問題是上下都是int s。當你用整數除int時,結果是一個int,任何十進制都被截斷。它看起來像你想要的百分比,所以你應該這樣做:

accu = ((float) up/down) * 100;