不计算程序中的最低和最高成绩。(C++)(流)
Doesn't calculate min and max grades in program. (c++) (fstream)
该程序的重点是打开并阅读一个文本文件,其中包含学生的学术代码 -> AEM 和他/她的总体成绩。然后,如果特定学生的成绩大于 5,它将在名为 success 的文本上写下他/她的学术代码,以及成绩等。我的问题是它正确计算了这 5 名学生的平均成绩,但没有计算最高和最低成绩。当我运行程序时,出现的窗口显示课程的正确平均值,但是最大和最小成绩始终为 0。谁能帮我?可能我没有以正确的方式比较它们。
#include <iostream>
#include <fstream>
using namespace std;
const int arraySize = 5;
int main(int argc, char** argv)
{
ifstream d;
d.open("students.txt");
ofstream b;
b.open("succesful.txt");
ofstream c;
c.open("unsuccesful.txt");
int aem;
double a[arraySize];
int min, max;
double grades, average;
grades = average = 0;
min = max = 0;
for (int i = 0; i < arraySize; i++)
{
d >> aem >> a[i];
grades = grades + a[i];
average = grades / arraySize;
if (a[i] >= 5) b << aem << " " << a[i] << endl;
else c << aem << " " << a[i] << endl;
}
for (int i = 0; i < arraySize; i++)
{
if (a[i] = max)
max = a[i];
break;
if (a[i] = min)
min = a[i];
break;
}
cout << "The average is:" << average;
cout << "Maximum is:" << max;
cout << "Minimum is:" << min;
d.close(); c.close(); b.close();
system("pause");
return 0;
}
int main(int argc, char** argv)
没有必要argc
和argv
来到这里。它可以只是int main()
.
int min, max;
double grades, average;
grades = average = 0;
min = max = 0;
在声明后分配值是不必要的且效率低下。此外,0
是一个整数,而不是浮点数。您可以初始化它们:int min = 0, max = 0;
double grades = .0, average = .0;
grades = grades + a[i];
可以缩短为grades += a[i];
average = grades / arraySize;
这句话毫无意义地存在于 for 循环中。您可以在循环后执行此操作。
for (int i = 1; i < arraySize; i++) {
你忘记了a
的第零个元素. 必须更换int i = 1;
才能int i = 0;
if (i >= max)
max = i;
if (i <= min)
min = i;
你把a[i]
误认为是i
.如果a[i]
和max
已经相等,则无需将a[i]
分配给max
.它们可以只是:
if (a[i] > max)
max = a[i];
if (a[i] < min)
min = a[i];
和
system("pause");
std::system
取决于系统环境,并且可能会发生意外行为。应将其替换为:
std::cout << "Press enter key." << std::endl;
std::cin.get();
相关文章:
- 计算每个节点的树高,帮助我解释这个代码解决方案
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- C++高阶模板
- 在STL - C++中按成绩对学生列表进行排序?
- 获取 SFML 窗口的 HWND 和高可用性?
- Opencv 恢复到比我设置的更高的分辨率
- 输入较高值时的分段代码
- 高精度双精度的 Sprintf 格式化问题
- 在Windows(C++)中使用USB相机拍摄高分辨率照片
- 较高值 n 的分割错误(例如 n=999997)
- 在 C++11 及更高版本中,有没有办法初始化初始值设定项列表中的向量?
- 将更高的优先级设置为 boost::asio 线程处理进程
- 在C++上实现高斯赛德尔迭代方法
- 如何在C++中为高分辨率时钟声明变量?
- 在 Windows/C++ 上使用多进程应用程序的高精度定时操作
- 为什么 Perf 具有如此高的上下文切换?
- 如何获得CMake Tools以在Visual Studio Code中编译具有C++11(或更高版本)功能的程序?
- 比较文件中的最佳平均成绩并打印学生的姓名
- C++:矩阵高斯消除不起作用:使用单维数组来存储元素
- 一段时间后 CPU 使用率高