2011-04-13 39 views
0

这是我到目前为止的代码。我想要做的是让程序显示超过60英寸的儿童数量和身高。该程序现在显示60英寸以上的儿童数量,但我也需要它显示60英寸以上儿童的身高。提前致谢!C++帮助。我有问题得到这个权利

#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; 
} 

回答

5

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

你已经有一个循环,通过你的阵列检查高度去所以它的加入是一件简单的事情,让你:

  • 也输出了高度检测时超过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输出是简单地添加空格,一个漂亮的格式触摸。这会导致输出类似:

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

另外,在大多数情况下,我倾向于选择\nendl。后者(见here)输出行的末尾刷新缓冲区,在某些情况下可能效率低下。

+0

非常感谢您的帮助。 – jgriff 2011-04-13 02:28:25

0

你只需要另一个for循环,就像计数高大的孩子一样,而不是计数,在身体中可以打印高度。