-2
我的代碼中的所有東西除了最後的數學運算外,都會輸出各種瘋狂的負數。任何建議來解決我混亂的代碼混亂?C++指針數學鬥爭
#include <iostream>
using namespace std;
double getScores(double *, int);
int sort(double *, int);
double calcAvg(double *, int); //function prototypes
void displayRpt(double *, int);
int main() {
int size;
cout << "Welcome to Daniel Mikos' Quiz Score Calculator" << endl << endl;
cout << "How many test scores would you like to enter? "; //prompt for # of test scores
cin >> size;
double *scores; //pointer for array
scores = new double[size]; //Declares a pointer to an array of doubles
getScores(scores, size);
sort(scores, size);
calcAvg(scores,size);
displayRpt(scores, size);
system("Pause");
return 0;
}
double getScores(double *scores, int size) { //prompts for scores
while (size <= 0) {
cout << "Error! There must be at least one score!" << endl;
cout << "Please try again!" << endl;
cout << "Enter number of test scores you would like to process: ";
cin >> size;
}
//scores = new double[size];
for (int i = 0; i < size; i++){
cout << "Enter test score " << (i +1)<< ": "; //prompt for each score
cin >> scores[i];
}
delete scores;
return 0;
}
int sort(double *scores, int size) { //sorts array from largest to smallest
double temp;
for (int i = 1; i <= size; i++) {
for (int j = 0; j < size; j++) {
if (scores[j + 1] > scores[j]) {
temp = scores[j];
scores[j] = scores[j + 1];
scores[j + 1] = temp;
}
}
}
return *scores;
}
double calcAvg(double *scores, int size) { //calculates average test score
double average;
double total = 0;
for (int i = 0; i < size; i++) {
total = total + scores[i];
}
average = total/size;
cout << endl <<"The average score: " << average <<endl <<endl;
return average;
}
void displayRpt(double *scores, int size) { //output report
for (int i = 1; i <= size; i++) {
cout << "Test score ("<< i <<"): "<<scores[i]<<endl;
}
}
多少/多大的數字?可能溢出 – user463035818
'displayRpt'在數組的末尾。 'sort'不符合你的期望。這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver
該排序將有一些超出範圍訪問對於'[j + 1]'當'j'具有其最大值時。 –