如何解决代码中的溢出问题?

huangapple go评论73阅读模式
英文:

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 ints 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.

huangapple
  • 本文由 发表于 2020年6月29日 10:49:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/62630498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定