0

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:

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);
}}
4

2 に答える 2

6

これは、s1 / 2を使用する場合、0.5 ではなく 0 に等しいためですint。int をdoubles(double) num / denまたは withにキャストしてみてください1.0 * num / den

于 2013-03-28T06:49:57.587 に答える
1

これはすべきです -

result = (double) num / den;

それ以外の場合、int / int の結果は小数部分のない int になります。

于 2013-03-28T06:49:03.210 に答える