英文:
How to get rid of an overflow in my code?
问题
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1;
int num2;
int num3;
int num4;
double numProduct;
double numAverage;
num1 = scnr.nextInt();
num2 = scnr.nextInt();
num3 = scnr.nextInt();
num4 = scnr.nextInt();
numProduct = num1 * num2 * num3 * num4;
numAverage = (num1 + num2 + num3 + num4) * 0.25;
System.out.print((int)numProduct + " ");
System.out.println((int)numAverage);
System.out.printf("%.3f ", numProduct);
System.out.printf("%.3f", numAverage);
}
}
英文:
I needed to create a code that inputs 4 numbers and outputs the product and average of these numbers. I needed to output them both as integers and decimals. However, to compute the product the second time (with decimals) I am supposed to input values like 100000, 200000, 300000, 500000, which causes an overflow and I'm not sure how to fix it. Thank you!
Here is my code:
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
int num1;
int num2;
int num3;
int num4;
double numProduct;
double numAverage;
num1 = scnr.nextInt();
num2 = scnr.nextInt();
num3 = scnr.nextInt();
num4 = scnr.nextInt();
numProduct = num1 * num2 * num3 * num4;
numAverage = (num1 + num2 + num3 + num4) * 0.25;
System.out.print((int)numProduct + " ");
System.out.println((int)numAverage);
System.out.printf("%.3f ", numProduct);
System.out.printf("%.3f", numAverage);
}
}
答案1
得分: 0
将乘法中的第一个 num1
进行手动转换即可。
numProduct = (double) num1 * num2 * num3 * num4;
问题在于对这 4 个 int
的乘法是在 int
类型中进行的,然后最终结果在赋值给 numProduct
时转换为 double
类型。您需要在乘法中将第一个 int
强制转换为 double
类型,以便整个乘法过程都在 double
类型中进行。
英文:
Manually casting the first num1
in your mulitplication will do it.
numProduct = (double) num1 * num2 * num3 * num4;
The problem was that the multiplication of the 4 int
s is done in int
, and then the final result is cast into a double
on assignment to numProduct
. You need to cast the first int
into a double
in the multiplication in order to force whole multiplication to be done in double
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论