我是java的初学者...如果语句后面跟着if if语句被按顺序计算,直到找到一个求值为true的语句,并且我已经看到了很多这样的例子。但是在这个程序中,两个语句(if和else if)都会被评估。为什么呢?
public int centeredAverage(int[] nums) {
int[] nums = {1, 1, 5, 5, 10, 8, 7};
int sum = 0;
int centered = 0;
int min = nums[0];
int max = nums[0];
int i = 0;
for (i = 0; i < nums.length; i++){
if (nums[i] < min){
min = nums[i];
} else if (nums[i] > max){
max = nums[i];
}
sum += nums[i];
centered = ((sum-max-min)/(nums.length-2));
}
return centered;
}
答案 0 :(得分:3)
因为他们处于更改i
的循环中,所以更改了nums[i]
,因此更改了if
&#39>是真的。
答案 1 :(得分:0)
你通过名为nums的引用传递了双精度数组,并且在方法中定义了一个看似奇怪的同名数组。你的for循环的起始索引也应该是1
答案 2 :(得分:0)
Im guessing this is the same problem from codingbat, next time copy and paste the problem desciption for others!
public int centeredAverage(int[] nums) {
Arrays.sort(nums); //sorts the array smallest to biggest
int total = 0;
//nums is already sorted, so the smallest value is at spot 0
//and the biggest value is at the end.
for(int a = 1; a < nums.length - 1; a++){ //avoid the first and last numbers
total += nums[a];
}
return total / (nums.length - 2); //need ( ) so we can substract 2 first
//Another way could simply sum all the elements then subtract from that sum
//the biggest and smallest numbers in the array, then divide by nums.length- 2, it is a
//little more complex, but allows a for : each loop.
}
But for you, well since you are a beginner, restate your strategy (algorithm), find the smallest and biggest numbers in the array, subtract that out of the sum of all elements in the array then divide that number by nums.length - 2, since we are ignoring 2 numbers.
答案 3 :(得分:-1)
使用if语句后跟else-if在这里没问题。我们在这里得到预期的结果。语句if和else-if都不会被执行。只执行该语句,根据逻辑,该语句为TRUE。 在这里,我们可以使用&#34; System.out.println&#34;来识别程序的工作情况。代码和控制台输出如下......
int[] nums = {1, 1, 5, 5, 10, 8, 7};
int sum = 0;
int centered = 0;
int min = nums[0];
int max = nums[0];
int i = 0;
for (i = 0; i < nums.length; i++)
{
if (nums[i] > min)
{
min = nums[i];
System.out.println("inside first if: " + i);
// taking value of i in SOP to get the iteration value
}
else if (nums[i] > max)
{
max = nums[i];
}
sum += nums[i];
centered = ((sum-max-min)/(nums.length-2));
System.out.println("inside else if: " + i);
// taking value of i in SOP to get the iteration value
}
System.out.println("centered value "
+ " " + centered);
您可以在每个程序中充分利用SOP来获取执行顺序。