问题描述
package expnum;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int numbers[];
int number;
String expression[]={"+" , "-" , "*" , "/"};
System.out.println("please enter 3 numbers:");
number=input.nextInt();
System.out.println("please enter 2 expression (+ , - ,* , /):");
if(number=='+')
System.out.println(number,"+",number);
else if(number=='-')
System.out.println(number,"-",number);
else if(number=='*')
System.out.println(number,"*",number);
else if(number=='/')
System.out.println(number,"/",number);
}
推荐答案
int number[3]
string operations[2]
for(i = 1 to 3)
{
print "Enter a number"
read numbers[i]
}
for(i = 1 to 2)
{
print "Enter an operation"
read operation[i]
}
这将读取您的输入,您还应该验证它们,以确保输入的内容是有效的输入,然后再次询问它们,直到输入的内容确定为止.
然后制作一个简单的子例程进行计算:
That will read your inputs, you should also validate them to make sure that what they enter is valid input and ask them again until what they enter is OK.
Then make a simple subroutine to do a calculation:
sub DoCalculation(string operation, int lhs, int rhs)
{
if (operation == "+")
{
return lhs + rhs
}
else if (operation == "-")
{
return lhs - rhs
}
// etc.
}
然后,您需要计算.操作顺序重要吗?还是应该使用简单的从左到右的方案?
从左到右的排序是这样的:
Then you need to calculate. Is order of operations important or should it use a simple left to right scheme?
Left to right ordering would be this:
int result = DoCalculation(operation[1], numbers[1], numbers[2])
result = DoCalculation(operation[2], result, number[3])
print result
正确的操作顺序应为:
Proper Order of Operations would be this:
int result = 0
if (operation[1] == "*" or operation[1] == "/")
{
// the first is a high order so it''ll be executed first regardless of whatever the second is
result = DoCalculation(operation[1], numbers[1], numbers[2])
result = DoCalculation(operation[2], result, number[3])
}
else if (operation[2] == "*" or operation[2] == "/")
{
// the first is a low order but the second is a high order so do it first
result = DoCalculation(operation[2], numbers[2], numbers[3])
result = DoCalculation(operation[1], numbers[1], result)
}
else
{
// both are low order
result = DoCalculation(operation[1], numbers[1], numbers[2])
result = DoCalculation(operation[2], result, number[3])
}
print result
这两个计算位都可以/应该循环化,但我将其留给读者练习:)
Both of the calculations bits could/should be loop-ified but I''ll leave that as an exercise for the reader :)
这篇关于该程序需要3个数字和3个expression(+,-,*,/),并且程序必须在表达式之间放置数字并给出答案.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!