0 c++
这是我到目前为止的代码.我要做的是让程序显示超过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;
}
Run Code Online (Sandbox Code Playgroud)
这非常接近,如果是家庭作业,这是一个很好的第一次尝试,所以我不介意帮忙.
你已经有一个循环通过你的数组检查高度,所以这是一个简单的问题,添加到那,所以你:
更改:
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;
Run Code Online (Sandbox Code Playgroud)
至:
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
Run Code Online (Sandbox Code Playgroud)
输出的改变numChildren只是添加空格,一个很好的格式化触摸.这应该导致输出类似于:
The heights of children over 60 inches are:
62
67
The number of children over 60 inches are:
2
Run Code Online (Sandbox Code Playgroud)
一些小的建议不会影响您的代码的性能可言,但我不认为我已经看到x = x + 1了几十年.C和C++这样做的方法通常是这样的++x.
此外,我倾向于选择\n到endl在大多数情况下.后者(见这里)输出一行结束并刷新缓冲区,这在某些情况下可能效率低下.