【问题标题】:How do i exclude negative numbers in an if loop?如何在 if 循环中排除负数?
【发布时间】:2015-08-28 04:28:47
【问题描述】:

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

谢谢

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

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")
}

}

【问题讨论】:

    标签: java loops if-statement


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢 :) 我之前尝试过,但忘记添加第二个 userInput。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-14
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多