C ++中最小数字未显示

时间:2013-04-23 19:23:29

标签: c++

#include <iostream>

using namespace std;

int main()
{  
    double sixty = 0.0;
    double fiftyfive = 0.0;
    double height[10];
    double tallest = 0.0;
    double shortest = 0.0;
    double average = 0.0;
    double total = 0.0;

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

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

    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] > 60)
        {
           sixty = sixty + 1;
          }
    }
    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] < 55)
        {
           fiftyfive = fiftyfive + 1;
        }
    }
    cout << "The number of students over 60 inches in height: " << sixty << endl;
    cout << "The number of students under 55 inches in height: " << fiftyfive << endl;

    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] > tallest)
        {
                      tallest = height[x];
        }
    }
    cout << "The tallest student is: " << tallest << endl;

    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] < shortest)
        {
                      shortest = height[x];
        }
    }
    cout << "The shortest student is: " << shortest << endl;

    for (int x = 0; x < 10; x = x + 1)
    {
        total = total + height[x];
    }
    average = total / 10;
    cout << "The average student height is: " << average << endl;   



    system("pause"); 
    return 0;
}

在上面,我需要吐出超过60英寸的学生,超过55英寸的学生,平均身高,最高身高和最短身高。

除了最短的高度外,一切正常。我为该部分代码返回零输出。

这是一个简单的代码,所以我想这是一个我忽略的简单问题。任何意见都表示赞赏。

6 个答案:

答案 0 :(得分:4)

    if (height[x] < shortest)
    {
                  shortest = height[x];
    }
最短为零的

将永远不会有比这更小的学生(除非你的学生从外界得到负高度;))。您需要使用height[0];初始化最短 同样在这种情况下,您可以从1

开始迭代学生
shortest = height[0];
for (int x = 1; x < 10; x = x + 1)
{
    if (height[x] > tallest)
    {
                  tallest = height[x];
    }
}

答案 1 :(得分:3)

将循环更改为

for (int x = 0; x < 10; x = x + 1)
{
    if (shortest == 0 || height[x] < shortest)
    {
                  shortest = height[x];
    }
}

或使用shortest数组中的第一个元素初始化height

你的代码不起作用,因为没有高度小于零。

答案 2 :(得分:1)

shortest的初始值为零

double shortest = 0.0;

并且循环找不到任何小于0的高度。

答案 3 :(得分:1)

for (int x = 0; x < 10; x = x + 1)
{
    if (height[x] < shortest)
    {
         shortest = height[x];
    }
}

由于shortest已初始化为0.0,如果您的height元素均不小于0.0,则您会看到shortest未更改。尝试以下方法:

shortest = height[0];
for (int x = 1; x < 10;  ++x)
{
    if (height[x] < shortest)
    {
         shortest = height[x];
    }
}

答案 4 :(得分:0)

除非你的学生身高不高,否则你的比较可能不对。

将“最短”高度设置为更大的值,否则比较永远不会成真。

答案 5 :(得分:0)

在将tallest数组作为输入后,

初始化shortestheight[0]height ...