简体   繁体   English

如何在不使用sum ++的情况下正确计算总和?

[英]How can i calculate the sum correctly without using sum++;?

So I'm working on a project currently and this step asked me to write a program which asks for numbers and when "-1" is entered, it will calculate the sum of all numbers entered except the -1. 因此,我目前正在一个项目上,此步骤要求我编写一个要求输入数字的程序,当输入“ -1”时,它将计算除-1之外所有输入数字的总和。 I simply fixed this by adding +1 after the loop, but im sure there is another "proper" way of doing it and i would like to learn how. 我只是简单地通过在循环后添加+1来解决此问题,但是我确定还有另一种“正确”的方法可以做到,我想学习如何做。

Any help is appreciated. 任何帮助表示赞赏。 ( Note: I've only been learning Java for around a week so ELI5 please ) (注意:我只学习Java大约一个星期,所以请使用ELI5)

public static void main(String[] args) {
            // program in this project exercises 36.1-36.5
            // actually this is just one program that is split in many parts

            Scanner reader = new Scanner(System.in);

            int numbertyped = 0;
            int sum = 0;

            System.out.println("Type numbers: ");

            while (numbertyped != -1) {

                numbertyped = Integer.parseInt(reader.nextLine());

                sum = sum + numbertyped;

            }
            sum++;
            System.out.println("Thank you and see you later!");
            System.out.println("The sum is " + sum);

EDIT: My program is complete now. 编辑:我的程序现在完成。 I used the solution of adding a break in the while loop and after adding the rest of the features i wanted, this is the end product: ( if anyone has tips on how to improve my code or make it more efficient please comment! ) 我使用了在while循环中添加一个break的解决方案,并在添加了我想要的其余功能之后,这才是最终产品:(如果有人对如何改进我的代码或使其更有效,有任何提示,请发表评论!)

    import java.util.Scanner;

    public class LoopsEndingRemembering {

        public static void main(String[] args) {
            // program in this project exercises 36.1-3


        // actually this is just one program that is split in many parts

        Scanner reader = new Scanner(System.in);

        int numbertyped = 0;
        int sum = 0;
        int howmany = 0;
        int evencounter = 0;
        int oddcounter = 0;

        System.out.println("Type numbers: ");

        while (true) {

            numbertyped = Integer.parseInt(reader.nextLine());

            if (numbertyped == -1) 
            {
                break;
            }

            if (numbertyped % 2 == 0)

            {
                evencounter++;
            } 

            else 

            {
                oddcounter++;
            }

            sum = sum + numbertyped;
            howmany++;

        }

        double average = (double) sum / howmany;

        System.out.println("Thank you and see you later!");
        System.out.println("The sum is " + sum);
        System.out.println("How many numbers: " + howmany);
        System.out.println("Average: " + average);
        System.out.println("Even numbers: " + evencounter);
        System.out.println("Odd numbers: " + oddcounter);

    }
}

You can terminate your loop as soon as -1 is entered, change 输入-1即可终止循环,更改

while (numbertyped != -1) {
    numbertyped = Integer.parseInt(reader.nextLine());

to something like

while ((numbertyped = Integer.parseInt(reader.nextLine())) != -1) {
    // ...

and the loop body will not be entered when -1 is assigned to numbertyped . 当将-1分配给numbertyped时,将不会输入循环体。

Based on your edits, I would suggest you might shorten sum = sum + numbertyped; 根据您的修改,我建议您缩短sum = sum + numbertyped; to sum += numbertyped; sum += numbertyped; and that you can calculate howmany by summing evencounter and oddcounter . 并且您可以通过将evencounteroddcounter相加来计算出howmany Like, 喜欢,

System.out.println("Type numbers: ");
while (true) {
    numbertyped = Integer.parseInt(reader.nextLine());
    if (numbertyped == -1) {
        break;
    }
    if (numbertyped % 2 == 0) {
        evencounter++;
    } else {
        oddcounter++;
    }
    sum += numbertyped;
}
int howmany = evencounter + oddcounter;
double average = (double) sum / howmany;

Quite often, C-like language users do not thing of using an "exit loop" ( break ) in similar situations. 经常,类似C的语言用户在类似情况下不会使用“退出循环”( break )。 You'd want something like this instead: 您想要的是这样的东西:

    while (true)
    {

        numbertyped = Integer.parseInt(reader.nextLine());

        if(numbertyped == -1)
        {
            break;
        }

        sum = sum + numbertyped;
    }

As a side note, a "forever loop" can be written with a for(;;) which some people say is better than a while(true) . 附带说明一下,“ forever loop”可以用for(;;)编写,有人说这比while(true)更好。 However, most people view while(true) as easier to read. 但是,大多数人认为while(true)更易于阅读。 Personally I use the for(;;) . 我个人使用for(;;) Either way both are optimized properly and thus you will get no runtime difference. 两种方法都可以正确优化,因此运行时不会有任何差异。

Reference about for(;;) : while (1) Vs. 关于for(;;)参考: while(1)Vs。 for (;;) Is there a speed difference? for(;;)是否存在速度差异?

I think in this case, you can just reverse the order of the statements in the while loop. 我认为在这种情况下,您可以反转while循环中语句的顺序。

        int numbertyped = 0;
        int sum = 0;

        System.out.println("Type numbers: ");

        while (numbertyped != -1) {

            sum = sum + numbertyped;

            numbertyped = Integer.parseInt(reader.nextLine());

        }

The first time through the loop, numberTyped is 0, which is perfect - it won't exit the loop, and it won't actually add anything to the sum. 循环中的第一次,numberTyped为0,这是完美的-它不会退出循环,并且实际上也不会添加任何东西。 After that, it won't change the sum until after you've checked whether it's -1. 在那之后,它直到您检查是否为-1时才改变总和。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM