为什么我的函数没有返回准确的计数
Why is my function not returning accurate count?
我一直在为一个补充跟踪器扩展代码,但我当前的函数没有返回大于平均值'mean'的准确数字计数,也没有返回低于平均值的整数计数。我还注释了代码中的两个问题,因为我不太明白为什么将数组设置为index[0]。我从这里的评论和寻找答案中学到了很多。非常感谢这个网站的存在!希望通过这个问题能学到更多。
function suppArray() {
var nums = new Array(); //create array
var sum = 0; //variable to hold sum of integers in array
var avg = 0; //variable to hold the average
var i;
var count = 0;
var count2 = 0;
var contents = ''; //variable to hold contents for output
var dataPrompt = prompt("How many numbers do you want to enter?", "");
dataPrompt = parseInt(dataPrompt);
for(i = 0; i <= dataPrompt - 1; i++) { //loop to fill the array with numbers
nums[i] = prompt("Enter a number","");
nums[i] = parseInt(nums[i]);
contents += nums[i] + " "; //variable that will be called to display contents
sum = sum + nums[i];
}
avg = sum / nums.length;
for(i = 0; i < nums.length; i++) { //loop to find the largest number
var biggest = nums[0]; //why does this have to be index 0 and not 'i' ?
if(nums[i] > biggest)
biggest = nums[i]; //largest integer in array
}
for(i = 0; i < nums.length; i++) { //loop to find smallest integer
var smallest = nums[0]; //why does this have to be the index 0 and not 'i' ??
if(nums[i] < smallest)
smallest = nums[i]; //smallest integer in array
}
for(count = 0; count < nums.length; count++) { //count of numbers higher than average
if(nums[i] > avg)
count = nums[i];
}
for(count2 = 0; count2 < nums.length; count2++) { //count of numbers lower than average
if(nums[i] < avg)
count2 = nums[i];
}
}
您的函数没有返回正确的值,因为您正确地分配了count
或count2
。如果在末尾运行代码,则count
和count2
将等于nums.length
。这是因为您正在for
循环中使用它们。在循环中,你也引用了i
,(我相信)在这一点上也等于nums.length
。
我想你想要这样的东西:
count = 0;
count2 = 0;
for(i = 0; i < nums.length; i++)
{
if(nums[i] > avg)
{
count++; //Increase the count of numbers above the average
}
else if(nums[i] < avg)
{
count2++; //Increase the count of numbers below the average
}
}
您可能想阅读scope和for循环,因为您对它们似乎有点困惑。
编辑
如果你想要数组中最大和最小的值,你可以这样做:
//Assign the values to the first element by default
var biggest = nums[0];
var smallest = nums[0];
for(var i = 1; i < nums.length; i++)
{
//Set biggest to the larger number, either biggest or the current number
biggest = Math.max(biggest, nums[i]);
//Set smallest to the smaller number, either biggest or the current number
smallest = Math.min(smallest, nums[i]);
}
注意:这假设您在数组中至少有1个值
相关文章:
- 从我的控制器返回一个不同于200的代码以触发ajax错误,这被认为是一种好的做法吗
- 我希望只有在我滚动页面后才能显示我的返回页首图标
- 我可以't返回我的json对象
- Angular 不返回我的自定义 JSON 文件
- 主干返回我的 JSON,但没有获取值
- AJAX:响应文本在本地返回我的整个PHP代码
- Backbone fetch返回我的模型的所有实例
- 如何返回我的表单错误
- responseText正在返回我的php文件的顶部
- 我怎么能等待谷歌远程呼叫返回我的结果之前继续
- 在.remove()和.append()之后返回我的事件按钮
- 上传onUploadSuccess没有返回我的数据
- 为什么我的jQuery不返回我的方程的值?
- 我如何返回我的项目在javascript和ASP.NET的当前域
- 如何正确地返回我的数据从AJAX调用(AngularJS)
- 为什么jquery没有返回我的值?
- Jquery点击函数,使用这个但返回我的窗口对象
- JSON 返回我的标头数据
- Instagram api没有返回我的以下列表
- Js: GetElementByID()不返回我的元素