显示数组中的最小值

时间:2013-04-17 03:11:47

标签: c++ arrays output minimum

好的,我还需要使用单独的10个元素阵列计算并显示每个高度增加5%后的高度。有任何想法吗?抱歉这一切。这是我第一次使用数组。

#include <iostream>

using namespace std;

int main()
{
    int MINheight = 0;
    double height[10];
    for (int x = 0; x < 10; x = x + 1)
    {
        height[x] = 0.0;
    }

    cout << "You are asked to enter heights of 10 students. "<< endl;
    for (int x = 0; x < 10; x = x + 1)
    {
        cout << "Enter height of a student: ";
        cin >> height[x];  
    }

    system("pause"); 
    return 0;
}

2 个答案:

答案 0 :(得分:3)

简单地循环:

MINheight = height[0];
for (int x = 1; x < 10; x++)
{
   if (height[x] < MINheight)
   {
      MINheight = height[x];
   } 
}
std::cout << "minimum height " << MINheight <<std::endl;

Side注意:你不应该使用大写字母命名一个局部变量,使用x因为数组索引也有点奇怪,虽然它们都工作正常但风格不好。

您也可以使用std::min_element,如下所示:

std::cout << *std::min_element(height,height+10) << std::endl; 
                               //^^using default comparison

要将元素放在具有更高高度的单独数组中并显示它们,请执行以下操作:

float increasedHeights[10] = {0.0};
for (int i = 0; i < 10;  ++i)
{
   increasedHeights[i] = height[i] * 1.05;
}

//output increased heights
for (int i = 0; i < 10;  ++i)
{
   std::cout << increasedHeights[i] << std::endl;
}

答案 1 :(得分:1)

基本上,您可以在输入时跟踪最小值,因此:

cout << "You are asked to enter heights of 10 students. "<< endl;

MINheight = numerical_limits<int>::max
for (int x = 0; x < 10; x = x + 1)
{
    cout << "Enter height of a student: ";
    cin >> height[x];  
    if(height[x] < MINheight)MINheight = height[x];
}
cout << "Minimum value was: " << MINheight << "\n";

这样做是创建一个变量,其值为最大可能值,然后当用户输入新值时,检查它是否小于当前最小值,如果是,则存储它。然后在最后打印出当前的最小值。

相关问题