计算两个整数之间的和 [英] calculating the sum between two integers

查看:82
本文介绍了计算两个整数之间的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以解决两个数字之间的和,但是如果第一个数字大于第二个数字,它将不会显示任何内容,但是如果我添加一个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;


}

推荐答案

它不在此方法中.请使用调试器进行检查.捕获该线程中的所有异常,看看会发生什么;它应该给您确切的位置.

方法的主体应该只是一行:
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;



当然,您写的不是一个错误,但是看起来很奇怪……

—SA



Of course, what you write is not a mistake, but looks weird…

—SA


尝试一下.

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;


	} 


这篇关于计算两个整数之间的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆