简体   繁体   中英

Computation error

I've been having trouble with my program. Im supposed to take in 3 variables and plug them into a formula to get an answer. My answer comes out to 0.0 and im not sure what i am doing wrong.

public double compute_cert (int years, double amount, double rate, double certificate)
{
    certificate = amount * Math.pow(1 + rate/100, years);
    return certificate;
}

The variables rate, amount and years are set up correctly but the answer certificate is always returned as 0.0

public static void main(String[] args)
{
    int years = 0;
    double amount = 0;
    double rate = 0;
    double certificate = 0;
    char ans;// allows for char 

    do{
        CDProgram C = new CDProgram(years, amount, rate, certificate);
        C.get_years();
        C.get_amount();
        C.get_rate();
        C.get_info();
        C.compute_cert(years, amount, rate, certificate);
        System.out.println ("Would you like to repeat this program? (Y/N)");
        ans = console.next().charAt(0);// user enters either Y or y until they wish to exit the program
   } while(ans == 'Y'||ans == 'y'); // test of do/while loop

}

Not sure what else to do. Thanks for the help

It looks like you are not assigning the local variables that you are passing into the computation function?

   years = C.get_years();
   amount = C.get_amount();
   rate = C.get_rate();
   info = C.get_info();

As it is, the code is just passing 0 for every parameter into your function. Multiplying by 0 will get you 0 . If you pass 0 , the following line will multiply 0 by some quantity.

certificate = amount * Math.pow(1 + rate/100, years);

It looks like your CDProgram class has fields for years , amount and rate , and your get_ method are prompting the user for the values.

That being the case, it doesn't make sense to pass parameters for them into your calculation method. I would change the method to this.

public double compute_cert () {
    certificate = amount * Math.pow(1 + rate/100, years);
    return certificate;
}

Then when you call it in main , don't pass any values in. This will just use the values from the fields in the CDProgram class.

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