我是 C++ 新手,我正在尝试编写一个程序来获取一组考试结果并将其以直方图形式打印出来。我正在分阶段编写代码,此时我试图让它接受考试分数,然后将它们打印在列表中,以确保它在继续进行直方图之前正常工作。
我的问题是,当我将数字输入数组然后打印它们时,我会得到一个奇怪的数字,例如我输入数字 1,2,3,4
预期的控制台输出: 1 2 3 4
实际输出: -858993460 1 2 3 4
所以我知道这一定是我的代码有问题,但我不确定有人可以帮忙吗?
代码:
void readExamMarks(int examMarks[], int sizeOfArray){
cout << "Please enter a set of exam marks to see a histogram for:" << endl;
for( int x = 0; x < sizeOfArray; x++){
cin >> x;
examMarks[x] = x;
}
}
void printExamMarks(int examMarks[], int sizeOfArray){
system("cls");
for(int x = 0; x < sizeOfArray; x++){
cout << examMarks[x] << endl;
}
}
int main()
{
int examMarks[5];
readExamMarks(examMarks, 5);
printExamMarks(examMarks,5);
system("PAUSE");
}
最佳答案
您正在为数组索引和数据重复使用 x
:
for( int x = 0; x < sizeOfArray; x++){
cin >> x;
examMarks[x] = x;
}
您需要为数组索引使用单独的变量:
int x = 0;
for( int idx = 0; idx < sizeOfArray; idx++){
cin >> x;
examMarks[idx] = x;
}
关于c++ - 数组列表打印错误的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15835062/