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

C++ calculations not printing in proper format

本文关键字:格式 式打印 计算 C++      更新时间:2023-10-16

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

在上述循环中,它不太可能为您提供预期的结果。因为dArrmain的本地,所以它可能有任何值。

更好的方法是镜像第二个循环,如下所示:

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

话虽如此,似乎根本没有真正的理由将这些数字存储在数组中(除非问题陈述中有一些关于这个问题的内容在这个问题中没有共享(。

您真正要做的就是保留总数和计数,以便计算出平均值。这可以像(我还更改了代码以使用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 << "nn";
return 0;
}