我是 C++ 的新手,我需要帮助来找出删除一组随机生成的数字的最低值的代码。到目前为止,这是我的代码:
//Create array and populate the array with scores between 55 and 10
// Drop lowest Score
#include <iostream>
#include <cstdlib>//for generating a random number
#include <ctime>
#include <iomanip>
#include <algorithm>
#include <vector>
using namespace std;
//function prototype
int *random (int);
int main()
{ int *numbers; //point to numbers
//get an array of 20 values
numbers = random(20);
//display numbers
for (int count = 0; count < 20; count++)
cout << numbers[count] << endl;
cout << endl;
system("pause");
return 0;
}
//random function, generates random numbers between 55 and 100 ??
int *random(int num)
{ int *arr; //array to hold numbers
//return null if zero or negative
if (num <= 0)
return NULL;
//allocate array
arr = new int[num];
//seed random number generator
srand(time (0));
//populate array
for (int count = 0; count < num; count++)
arr[count] = (rand()%(45) +55);
//return pointer
//
return arr;
}
对于这段代码,在函数返回随机数后,我将如何排序或找到最低分数以将其丢弃?
int main()
{ int *numbers; //point to numbers
//get an array of 20 values
numbers = random(20);
//display numbers
for (int count = 0; count < 20; count++)
cout << numbers[count] << endl;
cout << endl;
system("pause");
return 0;
}
非常感谢您的建议!
最佳答案
一般来说,要找到数组中的最小值,您可以遵循以下伪算法:
min = array[0] // first element in array
for (all_values_in_array)
{
if (current_element < min)
min = current_element
}
但是,您不能从静态数组中“删除”一个值。您可以考虑使用动态容器(例如 vector ),或者将最低值与最后一个值交换,并假装数组的大小少 1。另一个低级选项是在堆上创建您自己的动态数组,但是,这可能比您正在寻找的更复杂。
使用 vector 会容易得多。要删除最低的元素,你只需要 sort in reverse order , 然后 remove the last element .就个人而言,我建议使用 vector 。
关于c++ - 如何降低最低值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13461049/