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

huangapple go评论59阅读模式
英文:

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(&quot;Give a number: &quot;);
           int number = Integer.valueOf(scanner.nextLine());

           if (number == 0) {break;}
           if (number &gt; 0) {count = count + 1;}
           if (number &lt; 0) {count = count + 1;}
           if (number &lt; 0) {sum = sum - number;}
           if (number &gt; 0) {sum = sum + number;}
           if (number &gt; 0 &amp;&amp; number &lt; 0) {continue;}




       }
        System.out.println(&quot;The total count is: &quot; + count);
        System.out.println(&quot;The sum of the count is: &quot; + sum);

答案1

得分: 1

问题在于,如果传递一个负数,比如 -1,你会得到 sum = sum - (-1),这会变成 sum = sum + 1

你只需要将:

if (number &lt; 0) {sum = sum - number;}

改为:

if (number &lt; 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 &lt; 0) {sum = sum - number;}

To:

if (number &lt; 0) {sum = sum + number;}

Also you can shorten the if-else conditions like this:

if (number == 0) {
    break;
} else {
    count++;
    sum += number;
}

huangapple
  • 本文由 发表于 2020年8月17日 13:49:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/63445214.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定