繁体   English   中英

检查两个整数之和是否等于三分之一

[英]check if two integers sum to a third

好的,我正在做这个编程任务,需要一点帮助。

这是问题所在:

给定三个整数 abc,如果可以将其中的两个整数相加得到第三个,则返回 true。

twoAsOne(1, 2, 3) → true
twoAsOne(3, 1, 2) → true
twoAsOne(3, 2, 2) → false

这是我到目前为止所得到的:

public boolean twoAsOne(int a, int b, int c) {
  return a + b != c;
}

它一直说它不完全正确,我不知道我哪里出错了。

这个问题询问是否有可能将任何两个相加得到剩下的一个。 您的代码仅在前两个添加到第三个时进行测试

因此,twoAsOne(3,1,2) 应该返回 true,因为 3 = 1 + 2; 但您只是在检查 3 + 1 = 2 是否为假。

您只是在检查一种可能性,而且,最重要的是,您正在错误地检查它,因为如果 a + b == c(因为您使用的是!=运算符),您将返回 false。

我不会为你做作业,但完整的可能性列表是:

n1 = n2 + n3
n2 = n1 + n3
n3 = n1 + n2

这应该是一件简单的事情:如果其中任何一个为真,结果就应该为真。 否则结果应该是假的。

或者,提供一个更明显的线索:如果满足这些条件中的一个多个,则应该为 否则它应该是false

如果不为您编写代码,我不知道我能做得多明显:-)

更新:现在可能已经有足够多的时间来使家庭作业没有实际意义了,这是我的解决方案:

public boolean twoAsOne (int n1, int n2, int n3) {
    if (n1 == n2 + n3) return true;
    if (n2 == n1 + n3) return true;
    if (n3 == n1 + n2) return true;
    return false;
}

尽管最后两行可以替换为:

    return (n3 == n1 + n2);

我更喜欢(对我来说,无论如何)更具可读性的版本。

除了 itowlson 和 Pax 提供的答案之外,由于您正在处理整数,因此它们可能会溢出,例如

Integer.MAX_VALUE + 1 == Integer.MIN_VALUE

哪个在数学上不正确

您可能需要检查此类场景以使您的程序完整。

您的代码仅考虑 int a 和 int b 的总和。 该解决方案需要涵盖所有可能性,即“int a 和 int c 的总和”和“int b 和 int c 的总和”。 参考下面提到的代码,希望有帮助!

public boolean twoAsOne(int a, int b, int c) {
  return ((a + b == c) || (b + c == a) || (c + a == b));
}

伙计,我希望你现在得到答案......如果你还没有

public boolean twoAsOne(int a, int b, int c) {
    return ((a+b==c) || (a+c==b) || (b+c==a));
}

我可能已经很晚了,但我已将其最小化。 二合一

public boolean twoAsOne(integer a, integer b, integer c){
    return ((a+b) == c ? true : (a+c) == b ? true : (b+c == a)? true : false);
}
package get_third;

public class Get_third {
    int a , b ,c ;
    boolean third_value(int a , int b , int c){

    if(a+b==c||b+c==a||c+a==b)
    {
        return true;
    }
    else
        return false ;
    }

    public static void main(String[] args) {
        Get_third obj =new Get_third();
        System.out.println(obj.third_value(1, 2, 3));
        System.out.println(obj.third_value(3, 1, 2));
        System.out.println(obj.third_value(3, 2, 2));      
    }
}

// 开始

public boolean twoAsOne(int a, int b, int c) {

    if (a + b == c) {
        return true;
    }
    else if (a + c == b) {
        return true;
    }
    else if (b + c == a) {
        return true;
    }
    else {
        return false;
    }
}

// 结尾

暂无
暂无

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

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