由于某种原因,当在任何正数之前输入一个负数时,“正数之和”的最终calculatePositiveSum输出错误。似乎正在发生的事情是代替忽略负数,而是从总数中减去总和。因此,如果我的输入是(-4,2,3),它将说正数之和为1。我不确定该方法有什么问题。
/* 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
}
最佳答案
您正在为实际总和pos
分配数组中第一个元素的值。因此,如果第一个元素为负数,它将被添加到总和中(代码中没有检查它是否为正数)。
要解决此问题,请使用pos
初始化和0
(顺便说一句,它不是描述性名称)。然后从for
(而不是0
)在1
循环中进行迭代。
public static double computePositiveSum(double[] num, int count)
{
double pos = 0;
for (int i = 0; i < count; i++) {
if (num[i] > 0) {
pos = pos + num[i];
}
}
return pos;
}
注意:建议您使用更具描述性的名称来命名变量。我会用名称
pos
声明sum
。当然,这与结果无关,但是对于人们理解代码很有用。关于java - 仅当在数组中最后输入负数时程序才起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21345246/