简体   繁体   中英

java conversion from double to int for certain numbers

import java.util.Scanner;
public class Test1C
{
    public static void main(String[] args)
    {
        Scanner reader = new Scanner(System.in);
        System.out.print("Enter an integer between 1 and 50: ");

        double quo;
        int num = reader.nextInt();

        for(double a = 1; a <= num; a++)
        {
            quo = (num / a);
            System.out.println(quo);            
        }
    }
}

This is the code I currently am making to evaluate the list of quotients based on what number was inputted. Now the only thing my brain keeps farting on about is how to convert the whole numbers that are currently decimals into integers. However, the doubles (ex: 1.333) that are printed by this code are fine as is. I just can't figure out how to convert the whole number decimals (ex: 12.0) into whole number integers. Can someone help me?

you can do like that .

Double d = new Double(1.25);
int i = d.intValue();
System.out.println("The integer value is :"+ i);

yes you can :

String s = "1.333";
double d = Double.parseDouble(s);
int i = (int) d;

or

String s="1.333";
int i= new Double(s).intValue();

There is no general way to detect whether a double is truly an integer and a comparison of double and double or int must, generally, be handled with much care, but for the range of numbers in your program (and the upper bound could be raised considerably), this will work as you want:

    for(double a = 1; a <= num; a++)      {
        double quo = num/a;
        int iquo  = (int)quo;
        if( iquo == quo ){
           System.out.println(iquo);
        } else {
           System.out.println(quo);
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM