我正在尝试编写一个程序来计算并显示高于60英寸的学生的身高。例如:我需要它来计算和显示高于60英寸的学生数量并显示各自的高度。我不确定如何存储单独的值并显示它们的高度。我已经得到了计算高于60英寸的学生数量的计划,但我需要帮助显示他们的特定身高。
#include <iostream>
using namespace std;
int main()
{
double count60 = 0.0;
double height[10];
for (int x = 0; x < 10; x = x + 1)
{
height[x] = 0.0;
}
cout << "You are asked to enter heights of 10 students. "<< endl;
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter height of a student: ";
cin >> height[x];
if (height[x] > 60)
{
count60 = count60 + 1;
}
}
cout << "The number of students taller than 60 inches: "<< count60 << endl;
cout << "The heights of these students are: "
system("pause");
return 0;
}
答案 0 :(得分:3)
不确定我完全明白你的问题所在。
从您提供的代码中可以清楚地知道如何:
for
语句输入); if
语句更新计数);和cout <<
声明。因此将这些与以下内容结合起来应该是一件简单的事情:
for (int x = 0; x < 10; x = x + 1) {
if (height[x] > 60) {
cout << height << '\n';
}
}
答案 1 :(得分:1)
以下是代码:
#include <iostream>
using namespace std;
int main()
{
double count60 = 0.0;
double height[10];
for (int x = 0; x < 10; x = x + 1)
{
height[x] = 0.0;
}
cout << "You are asked to enter heights of 10 students. "<< endl;
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter height of a student: ";
cin >> height[x];
if (height[x] > 60)
{
count60 = count60 + 1;
}
}
cout << "The number of students taller than 60 inches: "<< count60 << endl;
cout << "The heights of these students are: ";
for(int i=0;i<10;++i)
if(height[i]>60)
cout<<' '<<height[i];
cout<<endl;
return 0;
}
顺便说一句,我认为count60最好是unsigned int。
答案 2 :(得分:1)
尝试使用std::vector
。它们基本上是数组的包装器,允许您动态添加值。在这种情况下,您将添加代码:
#include <vector> // obviously with the rest of the includes.
std::vector<int> tallPeople;
for (int x = 0; x < 10; x = x + 1)
{
if (height[x] > 60)
{
count60 = count60 + 1;
tallPeople.push_back(height[x]);
}
}
//...
for (int num = 0; num < tallPeople.size(); num++)
{
cout << tallPeople[num] << endl;
}
答案 3 :(得分:1)
在这里你......在空间利用方面不是最好但是避免了STL。
#include <iostream>
using namespace std;
int main()
{
int count60 = 0;
double height[10];
double maxheight[10];
for (int x = 0; x < 10; x = x + 1)
{
height[x] = 0.0;
}
cout << "You are asked to enter heights of 10 students. "<< endl;
for (int x = 0; x < 10; x = x + 1)
{
cout << "Enter height of a student: ";
cin >> height[x];
if (height[x] > 60)
{
maxheight[count60] = height[x];
count60 = count60 + 1;
}
}
cout << "The number of students taller than 60 inches: "<< count60 << endl;
for (int i = 0; i < count60; i = i + 1)
{
cout<<"The heights of these students are: "<< maxheight[i] << endl;
}
system("pause");
return 0;
}
答案 4 :(得分:0)
如果您想删除重复项,请执行此操作
//bubble sort
for(int i=0;i<9;i++)
{
for(int j=i+1;j<10;j++)
{
if(height[i]>height[j])
{
double temp = height[i];
height[i] = height[j];
height[j] = temp;
}
}
}
//print
for(int i=0;i<10;i++)
{
if(height[i]>60 && (i==0 || height[i]!= height[i-1]))
{
cout << ' ' << height[i];
}
}