2011-04-13 44 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循環,就像計數高大的孩子一樣,而不是計數,在身體中可以打印高度。