如何将exp转换为java exp

时间:2015-11-13 14:03:29

标签: java

我有一份作业

enter image description here

我不知道如何将表达式转换为Java。 有时我必须加括号,它会改变解决方案, 我不确定,如果我的代码是对的。

我写了这段代码:

double number1 = 10;
double number2 = 20;
double number3 = 30;

int sum = (int) (number1 + number2 + number3);
double average = sum / 3;

int product = (int) (number1 * number2 * number3);
double exp = (10.5 / number3) + (5 + number1 * number2) / (number3 - number1) * 12;

System.out.println("The sum is: " + sum);
System.out.println("The product is: " + product);
System.out.println("The average is: " + average);
System.out.println("The expression result is: " + exp);

3 个答案:

答案 0 :(得分:0)

int sum = (int) (number1 + number2 + number3);

将sum作为double ..不需要将其转换为int。您将失去精度。

int product = (int) (number1 * number2 * number3);

同样适用于此。

休息看起来不错。

答案 1 :(得分:0)

我只看到一个问题:

double average = sum / 3;

是整数除法,对于某些输入会失败(它仍然适用于您的数字)但它应该是这样的:

double average = sum / 3.0;
您可以将sum的类型更改为double

答案 2 :(得分:0)

每个人都帮助我。

我解决了这个问题

package home1;

public class Arithmetic {

    public static void main(String[] args) {

        int number1 = 10;
        int number2 = 15;
        int number3 = 35;

        int sum =  (number1 + number2 + number3);
        double average = sum / 3.0;

        int product = (number1 * number2 * number3);
        double exp = (10.5 / number3) + (5 + number1 * number2) / (number3 - number1) * 12;

        System.out.println("The sum is: " + sum);
        System.out.println("The product is: " + product);
        System.out.println("The average is: " + average);
        System.out.println("The expression result is: " + exp);
    }
}