我在这里有一个c ++代码。该代码用于计算某些文件中的数据。
#include<stdio.h>
#include<iostream>
#include <fstream>
using namespace std;
int main(){
//initiate file variable
ifstream inFile;
//other variable
int count, limit=30, time, remain, flag=0, time_quantum, arrival_time=30, var, total_process[30], data;
int wait_time=0, turnaround_time=0, rt[30], num_of_interrupts=0, num_of_jobs=0;
cout<<"Your job list :\n";
for(var = 1; var <= limit; var++){
//the purpose is the check weither looping is okay or not
cout<<""<<var;
//preparing array for the file
char nambuf[30];
std::snprintf(nambuf, sizeof(nambuf), "job%d.txt", var);
std::ifstream inFile;
//open file
inFile.open(nambuf);
//check file
if (!inFile) {
cout << " Unable to open file";
exit(1); // terminate with error
}
//read data from file .txt
while (inFile >> data) {
//calculate total process from data
total_process[var] += data;
++data;
}
//close file
inFile.close();
//print total process
cout << " Sum = " << total_process[var] << endl;
}
return 0;
}
代码按预期运行。但是,在执行总过程计算后会出现问题。 输出示例:
很抱歉,如果代码设计不佳。我仍然是编程新手。
答案 0 :(得分:2)
有一些问题。
1)C ++中的数组从0开始索引,而不是从1开始索引。这意味着当您有30个元素组成的数组时,允许的索引从0到29。但是在循环var
中,它从1迭代到30,因此当最后一个“真正”可访问元素是total_process[30]
时,最后一次迭代尝试使用total_process[29]
。这样的错误很难调试,因为当您在数组的边界之外写入元素时,会破坏周围的内存,因此您可以通过这种方式更改其他变量。要解决此问题,请使用for (var = 0; var < limit; var++)
进行迭代,或使用var - 1
这样的索引:total_process[var - 1]
。
2)默认情况下,变量和原始类型(例如int
)的数组未初始化,因此您不应访问此类未初始化的变量。始终确保使用某些变量时,该变量已具有一些分配的值。您可以使用int arr[30] = {0};
,int arr[30] = {}
或int arr[30]{}
之类的零来初始化数组。
也要小心,不要与初始化数组的第一种方法混淆:
int arr[30] = {1};
这不会用1初始化所有元素,而只是用1初始化arr[0]
并用0初始化所有其他元素。之所以起作用是因为您可以这样做:
int arr[30] = {1, 2, 3, 4, 5}; // all other will be 0
答案 1 :(得分:0)
我认为您从未初始化过结果数组total_process
。
所以您应该使用
对其进行零初始化。 int total_process[30] = { 0 };
当程序的运行方式不符合您的预期时,您应该使用调试器。这样一来,您就可以逐步执行该程序,并查看它在何处具有您没有想到的值或计算。