英文:
After that it should display the count and the total sum of the numbers entered. It adds the negative numbers for some reason. 0 to end
问题
import java.util.Scanner;
public class DoubleInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double count = 0;
double sum = 0;
while (true) {
System.out.println("Give a number:");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) { break; }
if (number > 0) { count = count + 1; }
if (number < 0) { count = count + 1; }
if (number < 0) { sum = sum - number; }
if (number > 0) { sum = sum + number; }
if (number > 0 && number < 0) { continue; }
}
System.out.println("The total count is: " + count);
System.out.println("The sum of the count is: " + sum);
}
}
英文:
Hi I'm pretty new to Java.
I've got this program i'm trying to finish. But for some reason it doesn't subtract the negative numbers from the sum. It only adds them.
here is the code:
import java.util.Scanner;
public class DoubleInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double count = 0;
double sum = 0;
while (true) {
System.out.println("Give a number: ");
int number = Integer.valueOf(scanner.nextLine());
if (number == 0) {break;}
if (number > 0) {count = count + 1;}
if (number < 0) {count = count + 1;}
if (number < 0) {sum = sum - number;}
if (number > 0) {sum = sum + number;}
if (number > 0 && number < 0) {continue;}
}
System.out.println("The total count is: " + count);
System.out.println("The sum of the count is: " + sum);
答案1
得分: 1
问题在于,如果传递一个负数,比如 -1
,你会得到 sum = sum - (-1)
,这会变成 sum = sum + 1
。
你只需要将:
if (number < 0) {sum = sum - number;}
改为:
if (number < 0) {sum = sum + number;}
另外,你可以将 if-else 条件缩写成这样:
if (number == 0) {
break;
} else {
count++;
sum += number;
}
英文:
The issue is that if you pass a negative number like -1
you will get sum = sum - (-1)
which becomes sum = sum + 1
.
You just need to change:
if (number < 0) {sum = sum - number;}
To:
if (number < 0) {sum = sum + number;}
Also you can shorten the if-else conditions like this:
if (number == 0) {
break;
} else {
count++;
sum += number;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论