我的 for 循環(huán)錯哪了,我為什么寫了個這么樣子的代碼?
public class HelloWorld{
? ? public static void main(String[] args){
? ? ? ? int num = 999;
? ? ? ? for (int count = 1;count < 10;count++){
? ? ? ? ? ? if (num >= 0 && num <999999999){
? ? ? ? ? ? ? ? System.out.println("它是個"+count+"位的數!");
? ? ? ? ? ? }else{
? ? ? ? ? ? ? ? System.out.println("輸入一個小于999999999的數,親!");
? ? ? ? ? ? }
? ? ? ? }
? ? }
}
2016-12-27
你打印的內容在循環(huán)體內,所以會打印10次,而且count你是定義的循環(huán)條件,這樣你count值和num沒有關系你看是不是想要這樣的效果
public class HelloWorld {
public static void main(String[] args) {
? ? ?int num = 999;
? ? ?int count=1;//兩位數要執(zhí)行一次,所有這里賦值1
? ? ?while (num/10 !=0) {
? ? ? ? ? ? count++;
? ? ? ? ? ? num/=10;
? ? }
? ? System.out.println("它是個" + count + "位的數!");
? ? }
}
另外for循環(huán)和while循環(huán)各有特點,;要用for循環(huán)的話,條件可以這樣寫
for(int s=num;s/10!=0;s/=10){
count++;
}
2016-12-27
你這個count的目的不是算位數嗎,但是你給他放在循環(huán)了 他就只能是相當于i的作用,就是循環(huán)使的
你應該利用除10,利用位數的改變來計算count的值 ,推薦你java入門第一季,視頻練習題有你的問題解決方法,當你的num=999,除10 ,除到0.999的時候 int值默認這個數是1,你吧這個當做循環(huán)的話,他才有可能計算位數啊
2016-12-27
你的循環(huán)判斷邏輯有問題,
不會走else里面的內容