0

好的,我还需要使用单独的 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;
}
4

2 回答 2

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;

旁注:你不应该命名一个以大写字母开头的局部变量,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;
}
于 2013-04-17T03:16:37.147 回答
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";

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

于 2013-04-17T03:16:26.587 回答