对于我的项目,用户输入一组数字,并执行一些计算以提供所需的输出。计算之一是查找输入的奇数之和。查看给定的测试用例,我注意到我的代码添加了负的奇数,而正确的测试用例却没有。有没有简单的解决办法?

谢谢

这是一些代码,我写的是减去几部分。

import java.util.Scanner;

public class Test
{
public static void main (String[] args)
{
    int min_interger = 0;
    int sum_of_pos = 0;
    int sum_of_odd = 0;
    int count_of_pos = 0;
    int userInput;

    Scanner consoleInput = new Scanner(System.in);

    do {userInput = consoleInput.nextInt();


    if(userInput % 2 != 0)
    {
        sum_of_odd = sum_of_odd + userInput;
    }

    while (userInput != 0);

    System.out.print("The sum of the odd integers is " + sum_of_odd + "\n")
}

}

最佳答案

确保添加奇数和大于零的数字

if(userInput % 2 != 0 && userInput > 0)
    {
        sum_of_odd = sum_of_odd + userInput;
    }

关于java - 如何在if循环中排除负数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32263349/

10-13 01:49