题目:
键盘录入两个数字number1和number2表示一个范围,求这个范围之内的数字和。
我写的代码:
public class Test {public static void main(String[] args) {Scanner sc = new Scanner(System.in);System.out.print("输入第一个数:");int number1 = sc.nextInt();System.out.print("输入第二个数:");int number2 = sc.nextInt();int max = 0;int min = 0;int sum = 0;if (number1 > number2){max = number1;min = number2;}else {max = number2;min = number1;}for (int i = min; i <= max; i++) {sum += i;}System.out.println("两数之和是:" + sum);}
}
代码有可能不是最优解答,如果有大佬也可以把更完美的代码发到评论区,或者给出优化的代码