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

时间:2018-09-25 03:55:32

标签: c++ arrays calculation

我正在做作业,当我运行程序时,我的计算结果显示为-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;
}

1 个答案:

答案 0 :(得分:0)

基于范围的for循环:

for (int val : dArr)

对集合val进行dArr迭代,对集合的索引进行 not 迭代。因此,当您尝试:

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

在上述循环中,不太可能为您提供预期的结果。由于dArr对于main是本地的,因此其中可能包含 any 值。

更好的方法是使用第二种方法来镜像第二个循环:

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

话虽如此,您似乎根本没有 real 理由将这些数字存储在一个数组中(除非问题语句中存在与此不共享的某些内容)问题)。

您真正需要做的就是保留总数和计数,这样您就可以算出平均值。那可能很简单(我也更改了代码以使用Herb Sutter的AAA风格,“几乎总是自动”):

#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;
}