gpt4 book ai didi

java - 如何修复计算错误?

转载 作者:行者123 更新时间:2023-11-29 06:12:34 26 4
gpt4 key购买 nike

我正在尝试编写一个程序,从用户那里读取 2 个数字并将它们相除。这是我到目前为止的代码:

import java.util.Scanner;

public class divideByZero {

public static int quotient(int numerator, int denominator)
{
return numerator / denominator;
}

public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);

System.out.print("Please enter the first number: ");

int numerator = scanner.nextInt();

System.out.print("Please enter the second number: ");

int denominator = scanner.nextInt();

int result = quotient( numerator, denominator );

float result2 = (float)result;

System.out.printf("\n The first number %d divided by the second number "
+ "%d = %f\n", numerator, denominator, result2 );

}

我在计算方面遇到了问题。例如,当我输入 3 除以 4 时,我得到结果 0.000000。如何获得精确到小数点后 2 位的结果?

最佳答案

在除以分子和分母之前将它们转换为 float 。

import java.util.Scanner;

public class divideByZero {

public static float quotient(float numerator, float denominator)
{
return numerator / denominator;
}

public static void main(String args[])
{
Scanner scanner = new Scanner(System.in);

System.out.print("Please enter the first number: ");

int numerator = scanner.nextInt();

System.out.print("Please enter the second number: ");

int denominator = scanner.nextInt();

float result = quotient( (float) numerator, (float) denominator );

System.out.printf("\n The first number %d divided by the second number "
+ "%d = %f\n", numerator, denominator, result );

}

关于java - 如何修复计算错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6301406/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com