[英]C++ help. I'm having problems getting this right
Here is the code that I have so far. 这是我到目前为止的代码。 What I'm trying to do is make the program display the number of children over 60 inches and their height.
我想做的是让程序显示60英寸以上的儿童人数及其身高。 The program now shows the number of children over 60 inches, but I also need it to display the height of the children over 60 inches.
该程序现在显示60英寸以上儿童的数量,但是我还需要它来显示60英寸以上儿童的身高。 Thanks in advance!
提前致谢!
#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;
}
That's very close, a good first attempt if it's homework, so I don't mind helping out a bit. 这非常接近,如果是家庭作业,这是一个很好的第一次尝试,因此我不介意提供帮助。
You already have a loop that goes through your array checking the heights so it's a simple matter of adding to that, so that you: 您已经有一个遍历数组的循环来检查高度,因此添加循环很简单,因此您:
Change: 更改:
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;
to: 至:
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
The change to the output of numChildren
was simply to add spaces, a nice formatting touch. 对
numChildren
的输出numChildren
的更改只是添加空格,这是一种不错的格式化方式。 This should result in output something like: 这应该导致输出类似:
The heights of children over 60 inches are:
62
67
The number of children over 60 inches are:
2
Some minor advice which doesn't affect your code performance at all, but I don't think I've seen x = x + 1
for decades. 一些小建议完全不会影响您的代码性能,但我认为数十年来我从未见过
x = x + 1
。 The C and C++ way of doing this is generally ++x
. 使用C和C ++的方法通常是
++x
。
In addition, I tend to prefer \\n
to endl
in most cases. 另外,在大多数情况下,我倾向于
\\n
而不是endl
。 The latter (see here ) outputs an end of line and flushes the buffers, which can be inefficient is some circumstances. 后者(请参阅此处 )输出行尾并刷新缓冲区,在某些情况下效率低下。
您只需要另一个for
循环,例如用来计数高个子的循环,而无需计数,您可以在体内打印高度。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.