java逻辑错误-10位小数未显示

wsewodh2  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(384)

这个问题在这里已经有答案了

整数除法:为什么1/3的结果==0((16个答案)
24天前关门。
我的程序允许用户计算两个数字,然后根据用户输入的运算符执行简单的计算。所以我的源代码是:

System.out.print("Enter First Number: ");
    int num1 = scanNum.nextInt();

    System.out.print("Enter Second Number: ");
    int num2 = scanNum.nextInt();

    System.out.print("Enter Operator (+, -, * or /): ");
    char opt = scanOpt.next().charAt(0);

    scanNum.close();
    scanOpt.close();

    switch (opt)    
    {
        case '+':
            float result = num1 + num2;
            System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
            break;

        case '-':
            result = num1 - num2;
            System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
            break;

        case '*':
            result = num1 * num2;
            System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
            break;

        case '/':
            result = num1 / num2;
            System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
            break;

        default:
            System.out.println("Invalid Operator!");
            break;

它工作得很好,但是每当它将两个数字相除时,比如“6.0/4.0”,第十个小数点就不会出现。正确的输出应该是:

Enter First Number: 6
Enter Second Number: 4
Enter Operator (+, -, * or /): /
6 / 4 = 1.5

但使用我自己的源代码,结果是:

Enter First Number: 6
Enter Second Number: 4
Enter Operator (+, -, * or /): /
6 / 4 = 1.0
von4xj4u

von4xj4u1#

double result;
        switch (opt)    
        {
            case '+':
                result = (double) num1 + num2;
                System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
                break;

            case '-':
                result = (double)num1 - num2;
                System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
                break;

            case '*':
                result = (double) num1 * num2;
                System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
                break;

            case '/':
                result = (double) num1 / num2;
                System.out.println(num1 + " " + opt + " " + num2 + " = " +result);
                break;

            default:
                System.out.println("Invalid Operator!");
                break;
        }
34gzjxbg

34gzjxbg2#

这是因为java将两个整数相除,从而得到一个整数输出。尝试将输入声明为float或alternativeley

1.0 * num1 / num2

这会将num1“转换”为浮点值。

相关问题