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风格,"几乎总是自动"(:
#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;
}
相关文章:
- C++ 将打印格式从整数 2255 更改为 $xx.xx
- 在 c++ 中以十六进制格式打印无符号字符(BYTE).使用 std::cout
- C++计算未以正确的格式打印
- 注意:"Entity_c::Entity_c(const Entity_c&)"被隐式删除,因为默认定义格式不正确:
- 如何以特定格式C++打印二叉搜索树
- C++:根据int值的基数使用条件格式打印
- 使用宏定义打印格式参数
- 如何在Qt中打印.xlsx格式
- 被隐式删除,因为默认定义格式不正确:
- 使用访问器以两种格式打印数据
- 悬挂式C 打印形状来自字符串阵列
- 测试用例之间的不同打印格式
- 如何总是在一行中获得C 的一个陈述?(格式/叮当式)
- 在 c++ 中使用 setfill() 以特定格式打印十进制数
- 如何以可读格式打印控制字符
- 如何在 c++ 中的字符串中显式打印“”
- 以树格式打印堆数组
- 如何打印可流式传输类型的 boost::变体
- 使用格式字符串打印类
- 如何将格式字符串打印到窗口中