Java 输出分数作为十进制程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15675809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:28:16  来源:igfitidea点击:

Java output fraction as a decimal program

javadecimal

提问by user1858350

I am supposed to create a program that takes a numerator and denominator value from the user then outputs the decimal value of that fraction. However, when I enter the values my output is 0.000000. Here's my code:

我应该创建一个程序,该程序从用户那里获取分子和分母值,然后输出该分数的十进制值。但是,当我输入值时,我的输出是 0.000000。这是我的代码:

import java.util.Scanner;
import java.util.Random;
public class fraction
{
   public static void main ( String [] args )
    {
       int num;
       int den;
       double result;


       num = getNum();
       den = getDen();
       result = getResult(num, den);

    printResult(num, den, result);

    }

    public static int getNum()
     {
    Scanner input = new Scanner (System.in);

    int num;

    System.out.print("Please enter the numerator: ");
    num = input.nextInt();

    return num;

     }

    public static int getDen()
        {
       Scanner input = new Scanner (System.in);

       int den;

       System.out.print("Please enter the denominator: ");
       den = input.nextInt();

       return den;

        }


public static double getResult(int num, int den)
{
    double result;
    result = num / den;
    return result;
}

public static void printResult(int num, int den, double result)
{
System.out.printf("The fraction %d / %d in decimal form is %f\n", num, den, result);
}}

回答by SteeveDroz

That's because 1 / 2is equal to 0, not 0.5 when you use ints. Try casting your ints into doubles either with (double) num / denor with 1.0 * num / den.

那是因为1 / 2当您使用ints时,它等于 0,而不是 0.5 。尝试将您的整数转换为doubles(double) num / den或 with 1.0 * num / den

回答by Sudhanshu Umalkar

This should do -

这应该做 -

result = (double) num / den;

Else, the result of int / int would be int without fractional part.

否则, int / int 的结果将是没有小数部分的 int 。