[英]What's wrong with my for-loop?
我試圖打印整數的每個數字,然后像這樣打印每個數字的總和。 循環有問題,但我似乎無法弄明白。 我希望它是這樣的:
Please enter a number: 194
1 * 100 = 100
9 * 10 = 90
4 * 1 = 4
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = ""+num;
double d = 0;
for(int i = 0; i < s.length(); i++) {
for(int j = s.length()-1; j >= 0; j--) {
d = Math.pow(10,j);
System.out.println(s.charAt(i) + " * " + d
+ " = " + (s.charAt(i)*d));
}
}
}
}
這是我的代碼的輸出:
Enter the number: 194
1 * 100.0 = 4900.0
1 * 10.0 = 490.0
1 * 1.0 = 49.0
9 * 100.0 = 5700.0
9 * 10.0 = 570.0
9 * 1.0 = 57.0
4 * 100.0 = 5200.0
4 * 10.0 = 520.0
4 * 1.0 = 52.0
您的代碼存在一些問題。
第一個問題是你不需要兩個循環,你只需要一個循環。
第二個問題是混淆char
和int
。 '0'
與0
; 相反, '0'
是表示該字符編碼的數值(結果為48)。 因此,為了獲得您想要的正確值,您應該在進行數學運算之前從char
減去'0'
。
for(int i = 0; i < s.length(); i++) {
d = Math.pow(10, s.length() - i - 1);
int value = s.charAt(i) - '0';
System.out.println(value + " * " + d
+ " = " + (value*d));
}
這將使它接近您想要的輸出。 盡管如此,它仍然顯示.0
,因為d
是double
。 使它成為一個int
來解決這個問題。
//This can be scoped to inside the loop, so you don't need to declare it beforehand
int d = (int)Math.pow(10,j);
import java.util.Scanner;
public class PrintEachDigits {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter the number: ");
int num = scan.nextInt();
String s = "" + num;
int len = s.length() - 1;
long d = 0;
if (len < 2) {
d = 1;//For single digit
} else {
d = (long)Math.pow(10, len);
}
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i) + " * " + d + " = "
+ ((s.charAt(i) - '0') * d));
d = d / 10;
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.