简体   繁体   中英

I have a Java logic question to solve about sum problem

I'm trying to get a list and sum it, but the logic is a bit odd.

For example

General cost = 
         {234.456,

         345.456,

         456.567,

         567.678}

I try to

find the sum

General cost Adds the numbers after the decimal point in each row, and if it does not exceed 1, the value after the decimal point is passed to the next row.

In the case above, I call the general cost one by one

1-> 234 (pass 0.456 to next)

2->345 (345.456+0.456=345.912 0.912 is passed to the next, and since the numbers after the decimal point are not over 1, the numbers after the decimal are passed as it is)

3->457 (456.567+0.912=457.479 0.479 is passed to the next, since the sum of the decimals is more than 1, add 1 to the value and pass the rest of the decimals to the next)

4->568 (567.678+0.479=568.157 passing 0.157 to the next, adding 1 to the value because the sum of the decimals was more than 1, and passing the rest of the decimals to the next)

Sum-> 1604 (to find the sum, round to one decimal place)

I'm trying to make it like this.

Can you do this? If you can do this, what kind of logic should you make it with?

You can achieve this by initializing a double-type local variable sum

double sum = 0; // Widening Casting

and the with a single loop iterate over your array and use proper statements eg if ... else if ... else to handle the addition operation including the last operation of rounding up i assume

sum += arrayItem; // Compound assignment operator

then you should be good.

Try this.

public static void main(String[] args) {
    double[] costs = {234.456, 345.456, 456.567, 567.678};
    double carry = 0;
    double total = 0;
    for (double cost : costs) {
        double sum = cost + carry;
        carry = sum % 1;               // get fractional part of sum
        double newCost = sum - carry;  // get integer part of sum
        total += newCost;
        System.out.printf("cost=%.3f new cost=%.0f carry=%.3f%n", cost, newCost, carry);
    }
    System.out.printf("total=%.0f%n", total);
}

output:

cost=234.456 new cost=234 carry=0.456
cost=345.456 new cost=345 carry=0.912
cost=456.567 new cost=457 carry=0.479
cost=567.678 new cost=568 carry=0.157
total=1604

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