有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java双精度+双精度=字符串?

我有一个问题,输出应该是双精度的,但它是字符串 我试图添加两个双值,但它是作为字符串提供的。我正在使用eclipse。目前该程序正在编译和运行。如果有人有时间,我将不胜感激。干杯,伙计们。这是源代码

import java.util.Scanner;

public class FutureInvestment 
{
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        System.out.println("Enter investment amount: ");
        double investmentAmount = input.nextDouble();

        System.out.println("Enter monthly interest rate: ");
        double monthlyInterestRate = input.nextDouble();

        System.out.println("Enter number of years: ");
        int numberOfYears = input.nextInt();

        double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate), numberOfYears * 12));
        System.out.println("Accumulated value is: " + futureInterestValue  + investmentAmount);


    }

}

共 (6) 个答案

  1. # 1 楼答案

    我认为把它改成这样会有效:

        double futureInterestValue = investmentAmount * ( Math.pow((1 + monthlyInterestRate / 100), numberOfYears * 12));
        System.out.println("Accumulated value is: " + (futureInterestValue  + investmentAmount));
    
  2. # 2 楼答案

    System.out.println("Accumulated value is: " + (futureInterestValue  + investmentAmount));
    

    在第一个+之后,Java将第一个字符串与第一个double连接起来,从而生成一个字符串。然后它对第二个double执行另一个连接。在生成字符串之前,需要先计算结果

  3. # 3 楼答案

    因为您在println中执行它,所以它执行字符串连接。如果要将double添加到一起,则需要使用()对它们进行分组

    试一试

    System.out.println("Accumulated value is: " + (futureInterestValue  + investmentAmount));
    
  4. # 4 楼答案

    您需要格式化输出。您可以使用DecimalFormat或尝试String#format函数:

    System.out.println(
        String.format("Accumulated value is: %.2f",
            futureInterestValue  + investmentAmount));
    

    所以你可以得到2位小数的输出。另外,我建议用您的结果创建一个变量,这样您就可以将代码转换为

    double accumulatedValue = futureInterestValue  + investmentAmount;
     System.out.println(
        String.format("Accumulated value is: %.2f", accumulatedValue);
    
  5. # 5 楼答案

    double accumulatedValue = futureInterestValue  + investmentAmount;
    System.out.println("Accumulated value is: " + accumulatedValue);
    

    试试这个

    您得到的字符串是连接的结果,因为连接到字符串的任何内容都将转换为字符串。因此,您需要像上面显示的那样提前完成值,或者需要括号

  6. # 6 楼答案

    缺少一些方括号,因此语句从左到右执行,从而在字符串后面追加double。您将需要以下内容:

    System.out.println("Accumulated value is: " + (futureInterestValue + investmentAmount));