C++帮助 - 我似乎无法弄清楚此代码的最后一部分

C++ Help - I can't seem to figure out the last part of this code

本文关键字:弄清楚 代码 一部分 最后 帮助 C++      更新时间:2023-10-16

我正在尝试让程序显示孩子的当前身高和估计身高。

我让它显示第一个孩子的前后,但无法显示其他孩子的估计身高。

如果有人能帮我解决这个问题,我将不胜感激。谢谢

这是我的代码:

#include <iostream>
using namespace std;
int main()
{
    double height [10];
    double chgHeight [10];
    for (int x = 0; x < 10; x = x + 1)
    {
        height[x] = 0.0;
        chgHeight[x] = 0.0;
    }
    cout << "You will be asked to enter the heights of ten children."<< endl;
    for (int x = 0; x < 10; x = x + 1)
    {   
        cout << "Enter height of child " << endl;
        cin >> height[x];
    }
    chgHeight[0] = height[0] * .05 + height[0];
    for (int x = 0; x < 10; x = x + 1)
    {   
        cout << "Child " << x+1 << ": Current " << height[x] << " Expected "<< chgHeight[x] << endl;
    }
    system("pause"); 
    return 0;
}
chgHeight[0] = height[0] * .05 + height[0];

您只设置了第一个孩子的chgHeight

编辑:

对于您的输出,您要遍历数组或高度,它由子编号(x(进行索引:

for (int x = 0; x < 10; x = x + 1)
{   
    cout << "Child " << x+1 << ": Current " << height[x] 
         << " Expected "<< chgHeight[x] << endl;
}

您的估计身高是根据孩子的当前身高计算出来的,您在这个循环中有这个身高(height[x](。所以,你有所有你需要的东西在那里输出估计的高度。

如果您不需要保存计算以备将来使用,那么实际上就不需要在代码中创建第二个chgHeight[]数组;只需计算并输出每个孩子在该循环中的估计身高。

您没有为其他孩子设置估计身高,只有第一个:

chgHeight[0] = height[0] * .05 + height[0];

把它放在一个循环中。

chgHeight[0] = height[0] * .05 + height[0];

这条线只计算第一个孩子的估计身高。您还需要将其放入一个循环中(将索引更改为循环变量(来计算所有10。