[英]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;
}
這非常接近,如果是家庭作業,這是一個很好的第一次嘗試,因此我不介意提供幫助。
您已經有一個遍歷數組的循環來檢查高度,因此添加循環很簡單,因此您:
更改:
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.