c++ - 为什么我的程序有时只能正确识别数组中的最高值和最低值?
问题描述
我正在编写一个作业程序,除其他外,它必须能够输出数组中的最高值和最低值。该数组中的十个数值,在程序的上下文中称为分数,由用户在早期输入。我有两个函数分别计算数组中的最大值和最小值。由于我无法弄清楚的原因,getHighScore 函数有时仅根据数组中存储的值正确确定最大值,而 getLowScore 函数返回的值始终确定最小值与 getHighScore 返回的值相同.
我已经尝试将我的代码与我自己过去的程序和在线的其他代码进行比较,以达到相同的目的,尽管它与一个这样的示例几乎相同,但我的 getLowScore 函数仍然无法按预期工作。我相信在我的程序中包含计算下面数组内容平均值的函数也是值得的,因为虽然它使用不同的命令,但它总是按预期工作,我不确定它与其他两个函数的区别。
//Stores the highest score in the array in the "highest" variable
int getHighScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the
//variable "size"
//POST: The largest value in the array is stored in the "highest" variable
{
int highest = 0;
highest = somearray [0]; //Set highest to the first element in the array
for (int index = 1; index < size; index++)
{
if (somearray [index] > highest);
highest = somearray [index];
}
return highest;
}
//Stores the lowest score in the array in the "lowest" variable
int getLowScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the
//variable "size"
//POST: The lowest value in the array is stored in the "lowest" variable
{
int lowest = 0;
lowest = somearray [0]; //Set lowest to the first element in the array
for (int index = 1; index < size; index++)
{
if (somearray [index] < lowest);
lowest = somearray [index];//
}
return lowest;
}
//Stores the mean of all the values in the array in the "average" variable
int getAvgScore (/*in*/const int somearray[], /*in*/int size)
//PRE: The contents of the array have been defined, as well as the
//variable "size"
//POST: The average value in the array is stored in the "average" variable
{
int totalScore = 0;
double average = 0;
//average = somearray [0]; //Set highest to the first element in the
array
for (int index = 0; index < size; index++)
{
totalScore += somearray [index];
}
average = totalScore / 10;
return average;
}
此代码可以编译,但逻辑错误使我无法实现预期的结果。
解决方案
就是这里的这些行:
if (somearray [index] > highest);
highest = somearray [index];
应该是这样的:
if (somearray [index] > highest) {
highest = somearray [index];
}
注意:你可能会或可能不会多次犯同样的错误,所以我会仔细检查我是否是你。
推荐阅读
- php - 在 WooCommerce 中获取产品类别和标签术语作为元关键字
- html - `display: block;` 在 `pre` 标签内的 `code` 标签内会创建不需要的新行,并且滚动时样式不会应用到全长
- mysql - MySQL 从存储过程中检索 last_insert_id
- html - 是表单标签“
- c# - Windows UIAutomation 未检测到窗口元素
- wordpress - 当 htaccess 不起作用时,如何重定向 Wordpress 子域上的 url?
- php - Laravel 为什么 $request->user() 关系不能正常工作?
- react-native - React Native Big Calendar 的 end 属性有问题
- python - Pyinstaller:找不到模块错误(熊猫)
- python - 将字符串类型转换为对象时出错