我在这个价格计算器上做错了什么?

时间:2014-08-31 23:21:39

标签: java calculator

我无法获得输出除0.0之外的任何数字我在这里做错了什么?

int num1 = 0;    
double d1 = 3.25, d2 = 0.45;
double numdozen = num1 / 12;
double numlooseeggs = num1 - (numdozen * 12);
double totaldozen = numdozen;
double totalloose = numlooseeggs;

Scanner fromKeyboard = new Scanner(System.in);

System.out.println("How many eggs do you want? They are $3.25/dozen or $.45/egg.");
num1 = fromKeyboard.nextInt();



double sum = totaldozen + totalloose;

System.out.println("$" + sum);

3 个答案:

答案 0 :(得分:2)

double numdozen = num1 / 12;

这会将numdozen初始化为0.0,这可能不是您的意图(如果是您的意图,则只需将其设置为0.0)。

numlooseeggs也被初始化为0.0,以及totaldozentotalloose

我认为你并不认为他们都是0。

最后double sum = totaldozen + totalloose;设置为0,无论您为num1指定了什么。

您可能想要做的是在获得用户输入后计算非常数双精度:

num1 = fromKeyboard.nextInt();
double numdozen = (double)num1 / 12;
double numlooseeggs = num1 - (numdozen * 12);
double totaldozen = numdozen;
double totalloose = numlooseeggs;

请注意,您应该在将num1除以12之前将其加倍,或者如果num1 <0,则numdozen将为0。 12。

答案 1 :(得分:1)

你把一切都变成了什么

int num1 = 0;                                    0

double d1 = 3.25, d2 = 0.45;

double numdozen = num1 / 12;                     0 / 12 = 0
double numlooseeggs = num1 - (numdozen * 12);    0 - (0 * 12) = 0
double totaldozen = numdozen;                    0
double totalloose = numlooseeggs;                0

答案 2 :(得分:1)

您在获取用户输入之前计算所有值,因此num10,强制其他所有内容为0。将之后的计算放在输入之后,如下所示:

int num1 = 0;
// don't do calculations that depend on input yet

Scanner fromKeyboard = new Scanner(System.in);

System.out.println("How many eggs do you want? They are $3.25/dozen or $.45/egg.");
num1 = fromKeyboard.nextInt();

// put the calculations that depend on input here
double d1 = 3.25, d2 = 0.45;
double numdozen = num1 / 12.0;
double numlooseeggs = num1 - (numdozen * 12);
double totaldozen = numdozen;
double totalloose = numlooseeggs;

double sum = totaldozen + totalloose;

System.out.println("$" + sum);