计算两个整数之间的和
问题描述:
我有一种方法可以解决两个数字之间的和,但是如果第一个数字大于第二个数字,它将不会显示任何内容,但是如果我添加一个if语句,则该方法将出错,提示无法访问代码
public int sum(int sum1,int sum2)
{
int sum0;
sum0 =(sum1 + sum2)*(sum1-sum2 + 1)/2;
返回sum0;
}
i have a method that solves the sum between two numbers but if the first number is greater than the second it wont display anything but if i add an if statement i get an error for the method saying unreachable code
public int sum(int sum1,int sum2)
{
int sum0;
sum0=(sum1+sum2)*(sum1-sum2+1)/2;
return sum0;
}
答
—SA
—SA
它不在此方法中.请使用调试器进行检查.捕获该线程中的所有异常,看看会发生什么;它应该给您确切的位置.
方法的主体应该只是一行:
It''s not in this method. Please check up, using the debugger. Catch all exceptions in this thread and see what happens; it should give you exact location.
And the body of your method should be just one line:
return (sum1 + sum2) * (sum1 - sum2 + 1) / 2;
当然,您写的不是一个错误,但是看起来很奇怪……
Of course, what you write is not a mistake, but looks weird…
尝试一下.
try this.
public static int sum(int sum1,int sum2)
{
int sum = sum1 > sum2 ? (sum1+sum2)*(sum1-sum2+1)/2 : (sum1+sum2)*(sum2-sum1+1)/2;
return sum;
}