簡體   English   中英

計算一個值出現的次數

[英]Count how many number of times a value appears

我想寫一個程序,告訴我有多少沒有。 所需值在 1 到 100 或任何其他范圍之間重復的次數。 例如:- 9 在 1 到 100 之間出現 20 次。

public class NumberCal {
    public static void main(String []args){
        int counter = 0;
        for(int i=1; i<=100; i++){
            while(i > 0){ 
                int LastDig = i%10;
                if(LastDig == 9){         
                    counter = counter+1 ;     
                    i = i/10;            
                } else{
                    i = i/10;
                }                        
            }     
        }                    
        System.out.println(counter);
    }
}

我試過了,但沒有 output。有什么建議嗎?

您將i用於外循環,但隨后也將其用於檢查並將其除以 10

int counter = 0;
for (int i = 1; i <= 100; i++) {
    int j = i;
    while (j > 0) {
        int LastDig = j % 10;
        if (LastDig == 9) {
            counter = counter + 1;
        }
        j = j / 10;
    }
}
System.out.println(counter);

細節

  • int i = 1使 i 為 1
  • i = i/10使 i 為 0
  • i++使 i 為 1
  • i = i/10使 i 為 0
  • i++使 i 為 1
  • 無限循環,因為你永遠不會每 100

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM