Java 阵列程序
谁能帮帮我吗。我很难修改代码的逻辑。假设数组的大小设置为100,则该程序应计算用户输入的数字的平均值,如果用户输入-99,程序将终止 我知道问题在while循环处理中Java 阵列程序,java,arrays,Java,Arrays,谁能帮帮我吗。我很难修改代码的逻辑。假设数组的大小设置为100,则该程序应计算用户输入的数字的平均值,如果用户输入-99,程序将终止 我知道问题在while循环处理中 Scanner input = new Scanner(System.in); int[] num = new int[100]; int ctr=0, sum=0, ave = 0; while(num[ctr]!= -99) { System.out.print("
Scanner input = new Scanner(System.in);
int[] num = new int[100];
int ctr=0, sum=0, ave = 0;
while(num[ctr]!= -99)
{
System.out.print("Enter number: ");
num[ctr]= input.nextInt();
sum += num[ctr];
ctr++;
}
System.out.print("Numbers are " );
for(int x = 0; x<ctr; x++)
{
System.out.print(num[x] + " ");
}
ave = sum / (ctr-1);
System.out.println("Average is " + ave);
}
}
扫描仪输入=新扫描仪(System.in);
int[]num=新的int[100];
int ctr=0,sum=0,ave=0;
while(num[ctr]!=-99)
{
系统输出打印(“输入编号:”);
num[ctr]=input.nextInt();
总和+=num[ctr];
ctr++;
}
系统输出打印(“数字为”);
对于(int x=0;xwhile循环,当数组被填充时,没有终止条件。(当输入100个整数时,ctr等于100。)while
循环的问题在于,它从不看刚进入的元素;它总是看它后面的元素。你应该在whilewhile
循环外读取第一个输入。因为当用户输入-99
时,在循环内你会增加ctr
,所以检查将使用错误的号码。因此,实际上,您从未检查您要检查的当前号码
int ctr=0, sum=0, ave = 0;
System.out.print("Enter number: ");
num[ctr]= input.nextInt();
while(num[ctr]!= -99)
{
sum += num[ctr];
ctr++;
System.out.print("Enter number: ");
num[ctr]= input.nextInt();
}
但是您需要处理用户只输入一个数字的情况,在这种情况下,您被零除,得到的平均值是错误的。您还应该执行以下操作:
ave = sum / (ctr);
而不是:
ave = sum / (ctr-1);
现在你会得到很好的结果。你应该在
while
循环外读取第一个输入。因为当用户输入-99
时,在循环内你会增加ctr
,所以支票的号码会错误。你能告诉我怎么做吗?我真的不知道你是谁。我试过模拟它,是的你说得对,谢谢你!它现在开始工作了。顺便说一句,我是一名It新生。我是java初学者。我有一个问题,这类似于启动输入吗?谢谢,我很高兴它有帮助:)我不明白你的意思,你能解释一下你的问题吗?