出於某種原因,當在任何正數之前輸入負數時,我的computePositiveSum最終輸出爲「正數的總和」是錯誤的。似乎發生的事情並不是忽略負數,而是從總數中減去它的總和。所以如果我的輸入是(-4,2,3),它會說正數的總和是1.我不確定這個方法有什麼問題。程序僅適用於輸入負數的數組last
/* Description: Write a program that reads in a sequence of numbers
(not necessary integers) from standard input until 0
is read, and stores them in an array. This is done
using iteration (choose for, while, or do while loop).
You may assume that there will not be more than 100 numbers.*/
import java.util.Scanner;
import java.text.DecimalFormat;
public class Assignment2
{
public static void main (String[] args)
{
Scanner scan= new Scanner(System.in);
int count=0;
double[] num= new double[100];
for(int i=0;i<num.length;++i)
{
num[i]= scan.nextDouble();
if (num[i] == 0) {
break; }
count++;
}
double min= findMin(num,count);
double pos= computePositiveSum(num, count);
int c= countNegative(num,count);
DecimalFormat fmt = new DecimalFormat ("0");
DecimalFormat fmt2 = new DecimalFormat ("$0.00");
System.out.println("The minimum number is " +fmt.format(min));
System.out.println("The sum of the positive numbers is "+fmt2.format(pos));
System.out.println("The total number of negative numbers is " +c);
}//End Main
public static double findMin(double[] num, int count)
{
double min = num[0];
for(int i=1;i<count;i++){
if(num[i] < min)
{
min = num[i];
}
}
return min;
}//end findMin
public static double computePositiveSum(double[] num, int count)
{
double pos=num[0];
for(int i=1;i<count;i++){
if(num[i] > 0)
{
pos=pos+num[i];
}
}
return pos;
}
public static int countNegative(double[] num, int count)
{
double a=num[0];
int c=0;
for(int i=0;i<count;i++){
if(num[i] < 0)
{
c++;
}
}
return c;
}//end countNegative
}
與您的問題沒有關係,但您可能希望在線上發佈時從源代碼中刪除您的姓名和學號。 – PakkuDon
你爲什麼要做'double pos = num [0];'?如果它是負面的呢? –
感謝您的抓住Pakku。 –