C++ 计算未以正确格式打印

C++ calculations not printing in proper format

我正在做家庭作业,当我 运行 我的程序时,我的计算显示为 -7.40477e+61。我使用 visual studio 作为我的 IDE,当我在在线检查器上检查我的代码时,它显示得很好。我不确定为什么所有内容都以这种格式打印。任何建议都会很棒!

#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>

using namespace std;

int main()
{

    double dArr[5];
    long lArr[7] = { 100000, 134567, 123456, 9, -234567, -1, 123489 };
    int iArr[3][5];
    char sName[30] = "fjksdfjls fjklsfjs";
    short cnt1, cnt2;
    long double total = 0;
    double average;
    long highest;

    srand((unsigned int)time(NULL));
    for (int val : dArr) {
        dArr[val] = rand() % 100000 + 1;
        cout << dArr[val] << endl;
    }

    for (int count = 0; count < 5; count++) {
        total += dArr[count];
        average = total / 5;
    }
    cout << endl;
    cout << "The total of the dArr array is " << total << endl;
    cout << endl;
    cout << "The average of the dArr array is " << average << endl;
    cout << endl;

    system("pause");
    return 0;
}

基于范围的 for 循环:

for (int val : dArr)

迭代val集合dArr不是该集合的索引。所以,当你尝试:

dArr[val] = rand() % 100000 + 1;

在上述循环中,不太可能给您期望的结果。由于 dArr 对于 main 是本地的,它可能有 任何 值。

更好的方法是镜像你的第二个循环,像这样:

for (int count = 0; count < 5; count++) {
    dArr[val] = rand() % 100000 + 1;
    cout << dArr[val] << endl;
}

话虽如此,似乎根本没有 真正 将这些数字存储在数组中的原因(除非问题陈述中有关于此的内容'分享了这个问题)。

您真正需要做的就是保留总数和计数,这样您就可以计算出平均值。这可能很简单(我还更改了代码以使用 Herb Sutter 的 AAA 样式,"almost always auto"):

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main() {
    const auto count = 5U;

    srand((unsigned int)time(NULL));

    auto total = 0.0L;
    for (auto index = 0U; index < count; ++index) {
        const auto value = rand() % 100000 + 1;
        cout << value << "\n";
        total += value;
    }

    const auto average = total / count;
    cout << "\nThe total of the dArr array is " << total << "\n";
    cout << "The average of the dArr array is " << average << "\n\n";

    return 0;
}