C++ 平均数组循环

标签 c++ arrays loops average

我目前正在尝试使用 C++。到目前为止,我已经学会制作一个程序,允许我输入 10 个变量以及 5 个已经赋值的变量,然后找到这些数字的平均值。但是我不知道该怎么做,我为数组做了一个 for 循环,但似乎没有找到平均答案。以下代码有什么问题?这是我目前所拥有的:

#include <iostream>

using namespace std;

int cole[10];
int sum = 0;
int main()
{
    int a = 10;
    int b = 10;
    int c = 10;
    int d = 10;
    int e = 35;
    cout << "Please input ten numbers, one at a time" << endl;
    cin >> cole[0];
    cin >> cole[1];
    cin >> cole[2];
    cin >> cole[3];
    cin >> cole[4];
    cin >> cole[5];
    cin >> cole[6];
    cin >> cole[7];
    cin >> cole[8];
    cin >> cole[9];
    cout << "There will now be 5 assigned variables, so that we have 15 variables" << endl;

    for(int x = 0; x < 10; x++ )
    {
        int sum = 0;
        cout << cole[x] << " ";
        sum += cole[x];
        cole[x]++;
    }
    sum += cole[0];
    cole[0]++;
    cout << "and " << a << " " << b << " " << c << " " << d << " " << e << endl;
    cout << "The average of these numbers is: ";
    sum = sum + a + b + c + d + e;
    cout << sum / 15;

}

提前致谢

最佳答案

请尝试此代码:IDEONE

#include <iostream>

using namespace std;

int cole[10];
int sum = 0;

int main()
{
    int a = 10;
    int b = 10;
    int c = 10;
    int d = 10;
    int e = 35;
    double avg = 0;
    cout << "Please input ten numbers, one at a time" << endl;
    for (int i=0;i<10;i++) {
        cin >> cole[i];
    }
    cout << "There will now be 5 assigned variables, so that we have 15 variables" << endl;

    for(int x = 0; x < 10; x++ )
    {
        cout << cole[x] << " ";
        sum += cole[x];
    }
    cout << "and " << a << " " << b << " " << c << " " << d << " " << e << endl;
    cout << "The average of these numbers is: ";
    sum = sum + a + b + c + d + e;
    avg = sum / 15.0;
    cout << avg;

}

请记住,平均值不应是整数值 - 它会将数字四舍五入到底数。请记住,您也可以在循环中将每个值输入到数组中,永远不要一个一个地输入。您还在循环中一次又一次地声明了“int sum = 0”,因此全局总和在循环内不可见。我也删除了一些不需要的代码。你可以看看,干杯

关于C++ 平均数组循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18529663/

相关文章:

c++ - 什么是 strlen 省略?

c++ - 如何使用 C++ 源代码和静态库创建 iOS 框架

java - 多维数组的替代数据结构

java - 如何访问从android中的restful web服务传递的json数组?

javascript - 使用 jQuery $.post 返回的数组

string - 如何连接字符串+我?

algorithm - 如何在 Processing 中创建一个简单的 l 系统

c++ - GPU 上的 OpenCV FAST 检测器

c++ - 从模板参数指向方法的指针

android - 我的应用程序不会运行,也不会切换 Activity