猿问

Java数减法,分解第二个数之和为1

当我可以在 java 中的 2 个数字之间进行减法时,我正在制作一个简单的 while 循环。本练习的唯一任务是:假设用户通过此方法插入 2 个数字(


Scanner keyboard = number.nextInt();

Scanner keyboard2 = number2.nextInt();

假设用户插入这 2 个数字:8 和 3 我不是要一个使 8 - 3 = 5 的程序


该程序只能做减法或 1 的加法。所以五次将五次转换为 -1 的减法。


因此,程序计算出 8 -1 -1 -1 -1 -1 = 3 而不是 8 - 3


// 8 - 5 或:


8 -1 = 7


7 - 1 = 6


// ....


4 - 1 = 3


练习不需要复杂的方法,也不需要for循环,只需要while


凤凰求蛊
浏览 148回答 3
3回答

慕哥9229398

根据我的观点,我认为您需要像您的示例一样的答案。因此,我为您制作了一个程序。在这个程序中如果你只先输入大数,你可以用except if语句,这是我的解决方案。import java.util.*;import java.lang.*;public class Stack2{&nbsp; &nbsp; public static void main(String args[]){&nbsp; &nbsp; &nbsp; &nbsp; Scanner sc= new Scanner(System.in);&nbsp; &nbsp; &nbsp; &nbsp; int num1=sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; int num2=sc.nextInt();&nbsp; &nbsp; &nbsp; &nbsp; if(num1<num2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Number 1 is less than number 2");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.exit(1);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; int x=num1-num2;&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(num1+" - "+num2+" --> is equal to "+ num1+" " );&nbsp; &nbsp; &nbsp; &nbsp; while(num1!=x){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print("-1 ");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; num1--;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("= "+x);&nbsp; &nbsp; }}

宝慕林4294392

您的代码几乎不需要更正。您尚未声明 Scanner 对象正确和偶数。试试这个代码,public static void main(String[] args) {&nbsp; &nbsp; Scanner sc = new Scanner(System.in);&nbsp; &nbsp; int num1 = sc.nextInt();&nbsp; &nbsp; int num2 = sc.nextInt();&nbsp; &nbsp; System.out.print(num1 + " - " + num2 + " --> Is equal to " + num1);&nbsp; &nbsp; while(num2 > 0) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(" - 1");&nbsp; &nbsp; &nbsp; &nbsp; num1 -= 1;&nbsp; &nbsp; &nbsp; &nbsp; num2--;&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(" = " + num1);&nbsp; &nbsp; sc.close();}

蝴蝶不菲

我不确定你是否想要这样的&nbsp; &nbsp; int num1 = 8;&nbsp; &nbsp; int num2 = 5;&nbsp; &nbsp; int res = num1- num2;&nbsp; &nbsp; boolean bandera = Boolean.TRUE;&nbsp; &nbsp; String salida = "";&nbsp; &nbsp; while(bandera)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if(num2 > 0)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; salida = salida +"-1";&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; num2--;&nbsp; &nbsp; &nbsp; &nbsp; }else&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; bandera = Boolean.FALSE;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println(num1 + salida + "=" + res);
随时随地看视频慕课网APP

相关分类

Java
我要回答