我正在尝试制作一个计算器,它从用户那里获取一个数字然后乘以我设置但我遇到了障碍。我需要让我的代码在每一步结束时取出产品然后乘以我设置的数字,但我无法弄清楚如何做到这一点。到目前为止,我所做的就是将每个步骤的用户数量乘以我不需要做的事情。
实施例: 用户输入8.我的代码取8并将其乘以我设置的数字,在本例中为6.然后我需要取出产品48并将其乘以我的另一个数字,然后将该产品再次乘以它,产品等等几个步骤。 我知道我不应该每次都输入userNum,但我不确定我应该放什么,我想确保代码至少部分功能。 :P如果令人困惑,请告诉我,我会编辑它。
int firstNum;
firstNum = 6;
int secondNum;
secondNum = 60;
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Ronnie. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello, " + userName + ". How many steps do you take in a ten second interval?");
String userNumString = userInputScanner.nextLine();
int userNum = Integer.parseInt(userNumString);
System.out.println("If you take " + userNum + " steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute: " + (userNum * firstNum) +"");
System.out.println ("Number of steps per hour: " + (userNum * secondNum) +"");
答案 0 :(得分:1)
使用中间变量:
System.out.println("If you take " + userNum + " steps in a 10 second " +
"interval, you could potentially achieve...");
long perMinute = userNum * 6;
System.out.println("Number of steps per minute: " + perMinute);
long perHour = perMinute * 60;
System.out.println("Number of steps per hour: " + perHour);
// ...
答案 1 :(得分:0)
如果你只做两步,你可以使用它。 否则你可以创建一个中间变量产品,并在每次打印前将结果保存在其中。
System.out.println ("Number of steps per hour: " + (userNum *firstNum* secondNum) +"");
答案 2 :(得分:0)
如果你知道它总是这样,你可以计算每个部分的数学:
int userNum = Integer.parseInt(userNumString);
System.out.println("If you take " + userNum + " steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute: " + (userNum * firstNum) +"");
System.out.println ("Number of steps per hour: " + (userNum * secondNum * firstNum) +"");
答案 3 :(得分:0)
据我所知,你想记录每个乘法值......
因此,假设您需要10个值:您可以使用数组:
int[] numbersToMultiply= [1,2,3,4,5,6,7,8,9,60];
int array[10];
Scanner userInputScanner = new Scanner(System.in);
System.out.println ("Hello, my name is Ronnie. What is your name?");
String userName = userInputScanner.nextLine();
System.out.println ("Hello, " + userName + ". How many steps do you take in a ten second interval?");
String userNumString = userInputScanner.nextLine();
for(int i=0;i<10;i++){
array[i] = userNum * numbersToMultiply[i];
}
System.out.println("If you take " + array[0] + " steps in a 10 second interval, you could potentially achieve...");
System.out.println ("Number of steps per minute: " + array[1] +"");
System.out.println ("Number of steps per hour: " array[10]"");