如何在java中找出十进制数字的总和。我已经尝试了像对待int值一样的常规方法,但是总和仅在精度数字之前和在精度数字之后才不清楚输出。搜索但没有答案。
public static void main(String[] args) {
double rem;
double sum = 0.0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a 5 digit decimal number:");
double num = sc.nextDouble();
while(num > 0) {
rem = num % 10;
sum = sum + rem;
num = num / 10;
}
System.out.println("Sum of digits = "+sum);
}
预期输出:
输入数字:12.12
总和:6.0
我得到的输出:
输入数字:12.12
总和:3.4666666666666655
感谢您的帮助。
答案 0 :(得分:3)
一一检查数字并将它们加到总和上。试试这个,
int sum = 0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a 5 digit decimal number:");
char[] s = sc.next().toCharArray();
for (int i = 0; i < s.length; i++) {
try {
sum += Integer.parseInt(s[i] + "");
} catch (Exception e) {
}
}
System.out.println("Sum of digits = " + sum);
答案 1 :(得分:3)
如果您不想使用异常处理,则应尝试此操作-
public static void main(String[] args) {
double sum = 0.0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a 5 digit decimal number:");
double num = sc.nextDouble();
String number = String.valueOf(num);
for (char c : number.toCharArray()) {
if(c!='.')
sum += Integer.parseInt(String.valueOf(c));
}
System.out.println("Sum of digits = " + sum);
}
答案 2 :(得分:3)
这是在Java 8+中完成此操作的简单方法(注释中的解释):
class Main{
public static void main(String[] a){
java.util.Scanner scanner = new java.util.Scanner(System.in);
String input = scanner.nextLine(); // Get the input-decimal as String
int sumOfDigits = input.replaceAll("[^0-9]", "") // Remove all non-digits from the input-String
.chars() // Convert it to a stream of characters
.map(c -> c-48) // Convert the character to a digit
.sum(); // Sum everything together
System.out.println("Sum of digits = "+sumOfDigits);
}
}
答案 3 :(得分:1)
public static void main(String[] args) {
double sum = 0.0;
Scanner sc = new Scanner(System.in);
System.out.println("Enter a 5 digit decimal number:");
double num = sc.nextDouble();
String number = String.valueOf(num);
for (char c : number.toCharArray()) {
try {
sum += Integer.parseInt(String.valueOf(c));
} catch (NumberFormatException e) {
// ignore the .
}
}
System.out.println("Sum of digits = " + sum);
}