我正在做家庭作业,当我运行我的程序时,我的计算显示为 -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 样式,“几乎总是自动”):
#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;
}
关于C++ 计算未以正确格式打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52490360/