Java:错误:可能会丢失精度

时间:2013-06-27 21:21:12

标签: java

我的程序几乎准备好了,但是,我似乎无法将总和输出为“3.2”或“5.2”之类的数字。出于某种原因,它只返回值为2.0或3.0或4.0,就像最后一个.0的整数一样。有什么帮助吗?

import java.io.Console;
import java.util.Scanner;
/**
 *
 * @author binka
 */
public class Samelson_Lincoln_Lab6 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Scanner in = new Scanner(System. in );
        System.out.println("Please enter a number?");
        int number = in .nextInt();
        double[] array = new double[number];
        System.out.println();
        int sign = 0;
        double term = 0;
        for (int i = 1; i < array.length; i++) {
            if (sign == 0) {
                term = Math.abs((4.0 / ((2.0 * i) - 1.0)));
                array[i] = term;
                sign = 1;
            } else if (sign == 1) {
                term = ((4.0) / ((2.0 * i) - 1));
                array[i] = -term;
                sign = 0;
            }
            System.out.println(array[i]);
        }
        boolean choice = true;
        while (choice = true) {
            System.out.println("Would you like to see the sum?: (Y or N)");
            String choicesum = in .next();
            choicesum.toUpperCase();
            if ("Y".equals(choicesum)) {
                double sum = computeSum(array);
                System.out.println("Your sum is: " + sum);
                choice = false;
                break;
            } else if ("N".equals(choicesum)) {
                System.out.println("See ya!");
                choice = false;
                break;
            } else {
                System.out.println("Not a correct response, try again!");
            }
        }
    }

    public static int computeSum(double[] array) {
        double sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum = sum + array[i];
        }
        return sum;
    }
}

1 个答案:

答案 0 :(得分:8)

while (choice = true) {

至少应该

while (choice == true) {

甚至更好

while (choice) {

要修复实际错误,请从

更改方法签名
public static int computeSum(double[] array) {

public static double computeSum(double[] array) {