简体   繁体   English

将某些数字从double转换为int的java

[英]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. 但是,按此代码打印的双打(例如:1.333)是可以的。 I just can't figure out how to convert the whole number decimals (ex: 12.0) into whole number integers. 我只是不知道如何将整数小数(例如:12.0)转换为整数整数。 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: 没有通用的方法来检测double是否是真正的整数,通常必须非常小心地处理double和double或int的比较,但是对于程序中的数字范围(可能会提高上限)相当),这将根据您的需要工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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