2011-04-21 203 views
1

當我運行程序時,它結束了平均值,但它不會循環!有誰看到我做錯了,我指出了正確的方向循環不工作

#include <iostream> 
#include <iomanip> using namespace std; 

//function prototypes 

void getTestScores(double &score1, double &score2, double &score3); 
double calcAverage(double &score1, double &score2, double &score3); 
void displayAverage(double avg); 

int main() 
{ 
    //declare variables 
    double score1 = 0.0; 
    double score2 =0.0;  
    double score3 = 0.0; 
    double avg = 0.0; 

    //display average in fixed-point notation 
    getTestScores(score1,score2,score3);  
    calcAverage(avg); 
    displayAverage(avg); 

    //enter scores 
    while (avg != -1); 
    { 
     cout << "score 1 (negative number to stop): "; 
     cin >> score1; 
     cout << "Enter score 2(negative number to stop): "; 
     cin >> score2; 
     cout << "Enter score 3(negative number to stop): "; 
     cin >> score3; 

     calcAverage(score1, score2, score3); 
     displayAverage(avg); 

     return 0; 
    } 
} //end of main function 

//*****function prototypes***** 
void getTestScores(double &score1, double &score2, double &score3) 
{ 
    cout << "Enter score 1(negative numberto stop): "; 
    cin >> score1; 
    cout << "Enter score 2(negative number to stop): "; 
    cin >> score2; 
    cout << "Enter score 3(negative number to stop): "; 
    cin >> score3; 
} //end 

double calcAverage (double &score1, double &score2, double &score3) 
{ 
    double average = 0.0; 
    average = calcAverage(score1, score2, score3); 

    return average; 
} //end of clacAverage 

void displayAverage(double avg)  
{ 
    cout << fixed << setprecision(1); 
    cout << "Average: " << avg << endl; 
} //end 
+1

使用4位代碼的每個語句之前,或只選擇整個代碼,點擊'{}'本編輯器選項卡上。 – Mahesh 2011-04-21 06:48:42

+0

爲什麼你需要'calcAverage'中的三個參數,就像這個'double calcAverage(double&score1,double&score2,double&score3);'但是給出這樣一個參數'calcAverage(avg);'?我不是一個C++的男孩我很抱歉,如果我問的是noob.Also我認爲你應該在(平均!= -1)' – Bastardo 2011-04-21 06:52:57

+0

(平均!= -1)之後移除';':不要直接比較浮點數(請參閱http://how-to.wikia.com/wiki/Howto_compare_floating_point_numbers_in_the_C_programming_language) – stefaanv 2011-04-21 07:08:44

回答

7

還有就是你while()循環後一個分號。嘗試刪除它。

4

您有returnwhile塊。返回將停止一切,包括循環。只有Python(AFAIK)允許循環返回並使其循環。

0

@Katie:你的代碼是否可以編譯?你的calcAverage(平均);函數調用與您定義它的方式不同。你忘了添加代碼重載函數與(同名)簽名calcAverage(雙)?

順便說一句,在while()之後刪除分號並且它可能正常運行。在你檢查我的問題之後試試這個。

0

返回將結束循環並將控制權返回到函數的調用位置。 此外,它似乎並沒有像在循環體中再次初始化avg一樣?返回的魅力,但不存儲它 應該

avg = calcaAverage(1,2,3)