#include <iostream>
using namespace std;
int main() {
int scores [9] = { 100, 80, 60, 75, 95, 65, 85, 40, 70 };
int total = 0;
for (int i = 0; sizeof(scores); i++) {
total += scores[i];
}
double average = (double) total/sizeof(scores);
cout << average << endl;
cin.get();
return 0;
}
錯誤消息:在TestProject.exe中0x002918F5引發異常:0xC0000005:訪問衝突讀取位置0x003A0000。Noob C++人:爲什麼我的數組不工作?
這段代碼有問題,但找不到它。只是試圖從Java中學習C++中的數組。謝謝。
'的sizeof(得分)'是以字節爲單位的陣列的長度。一個'int'使用多個字節。你需要除以sizeof(int)或sizeof(scores [0])或sizeof(* scores)'來獲得元素的數量,無論哪一個漂浮在你的船上。 –
請注意,您可以使用基於範圍的for循環來循環普通數組:'for(auto s:scores)total + = s;'。 – juanchopanza