问题已附加,因此我尝试解决此问题,但我得到的输出很大,这可能是垃圾数据,因此绝对不正确。
这是我的代码
#include <iostream>
#include <fstream>
using namespace std;
const int size=8;
void readData(char filename[], int list[], int size)
{
ifstream fin;
fin.open("HW4_Q1data.txt");
int value=0;
for(int i=0;i<30;i++)
{
fin>>filename[i];
value=filename[i];
if (value >= 0 && value <= 24)
list[0]++;
else if (value >= 25 && value <= 49)
list[1]++;
else if (value >= 50 && value <= 74)
list[2]++;
else if (value >= 75 && value <= 99)
list[3]++;
else if (value >= 100 && value <= 124)
list[4]++;
else if (value >= 125 && value <= 149)
list[5]++;
else if (value >= 150 && value <= 174)
list[6]++;
else if (value >= 175 && value <= 200)
list[7]++;
}
fin.close();
}
void print(int list[], int size)
{
cout << " Range"<<'\t'<<"# of students"<<endl;
cout << "0-24: " <<'\t'<<list[0] << endl;
cout << "25-49: " << '\t'<<list[1] << endl;
cout << "50-74: " <<'\t'<< list[2] << endl;
cout << "75-99: " <<'\t'<< list[3] << endl;
cout << "100-124: " <<'\t'<< list[4] << endl;
cout << "125-149: " <<'\t'<<list[5] << endl;
cout << "150-174: " <<'\t'<< list[6] << endl;
cout << "175-200: " <<'\t'<< list[7] << endl;
}
int main()
{
char filename[70];
int list[size];
readData(filename,list,size);
print(list,size);
return 0;
}
最佳答案
正如 VTT 所说,您没有初始化列表值,因此它那里有垃圾值。您应该用 0 来初始化它们。
int main() {
// filename stuff
int list[size];
for(int i = 0 ; i < size; i++) {
list[i] = 0;
}
// read and write functions
}
此外,据我所知,我可以从问题 char filename[]
应该用作文件名: fin.open(filename);
编辑
大部分程序,可以解决您的问题:
void readData(char filename[], int list[], int size)
{
ifstream fin;
fin.open(filename);
int value;
for(inti= 0; i<30; i++) {
fin>>value;
if (value >= 0 && value <= 24)
list[0]++;
// ... other if else stuff
}
fin.close()
}
// print stuff
int main() {
int list[size] = {0}; // initialize the list with 0.
readData(*filename*, list, size); // replace *filename* with the real file name
print(list,size);
return 0;
}
关于C++编程数组以查找范围内的整数个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44045841/