繁体   English   中英

C ++帮助。 我在解决这个问题时遇到了问题

[英]C++ help. I'm having problems getting this right

这是我到目前为止的代码。 我想做的是让程序显示60英寸以上的儿童人数及其身高。 该程序现在显示60英寸以上儿童的数量,但是我还需要它来显示60英寸以上儿童的身高。 提前致谢!

#include <iostream>
using namespace std;
int main ()
{
    double childHeight[10];
    int numChildren = 0;

    for (int x = 0; x < 10; x = x + 1)
    {
        childHeight[x] = 0.0;
    }
    cout << "You will be asked to enter the height of 10 children." << endl;
    for (int x = 0; x < 10; x = x + 1)
    {
        cout << "Enter the height of child: ";
        cin >> childHeight[x];
    }
    cout << "The number of children over 60 inches are: "<< endl;
    for (int x = 0; x < 10; x = x + 1)
    {
        if (childHeight[x] > 60)
        {                
           numChildren = numChildren + 1;                
        }  
    }
    cout << numChildren << endl;
    system("pause"); 
    return 0;
}

这非常接近,如果是家庭作业,这是一个很好的第一次尝试,因此我不介意提供帮助。

您已经有一个遍历数组的循环来检查高度,因此添加循环很简单,因此您:

  • 当检测到时也输出超过60的高度;
  • 对打印的内容稍作更改,以使该顺序有意义。

更改:

cout << "The number of children over 60 inches are: " << endl;
for (int x = 0; x < 10; x = x + 1)
{
    if (childHeight[x] > 60)
    {                
       numChildren = numChildren + 1;                
    }  
}
cout << numChildren << endl;

至:

cout << "The heights of children over 60 inches are: " << endl;    // ADD
for (int x = 0; x < 10; x = x + 1)
{
    if (childHeight[x] > 60)
    {                
       numChildren = numChildren + 1;                
       cout << "    " << childHeight[x] << endl;                  // ADD
    }  
}
cout << "The number of children over 60 inches are: " << endl;    // MOVE
cout << "    " << numChildren << endl;                            // CHNG

numChildren的输出numChildren的更改只是添加空格,这是一种不错的格式化方式。 这应该导致输出类似:

The heights of children over 60 inches are:
    62
    67
The number of children over 60 inches are:
    2

一些小建议完全不会影响您的代码性能,但我认为数十年来我从未见过x = x + 1 使用C和C ++的方法通常是++x

另外,在大多数情况下,我倾向于\\n而不是endl 后者(请参阅此处 )输出行尾刷新缓冲区,在某些情况下效率低下。

您只需要另一个for循环,例如用来计数高个子的循环,而无需计数,您可以在体内打印高度。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM