2015-11-19 57 views
0
while (counter < total) 
{ 
inFile >> grade; 
sum += grade; 
counter++; 
} 

上面是我的原始程序的while循環,下面是我將它轉換爲for循環的嘗試。如何將一個while循環轉換爲C++中的for循環?

for (counter = 0; counter < total; counter++) 
{ 
    inFile >> grade;   
    cout << "The value read is " << grade << endl; 
    total = total + grade; 
} 

這是一個簡單的程序來獲得成績平均值。這裏是整個程序:

#include <iostream> 
#include <fstream> 
using namespace std; 
int average (int a, int b); 
int main() 
{ 
// Declare variable inFile 
    ifstream inFile; 
// Declare variables 
    int grade, counter, total; 
// Declare and initialize sum 
    int sum = 0; 
// Open file 
    inFile.open("input9.txt"); 
// Check if the file was opened 
    if (!inFile) 
    { 
    cout << "Input file not found" << endl; 
    return 1; 
    } 
// Prompt the user to enter the number of grades to process. 
    cout << "Please enter the number of grades to process: " << endl << endl; 
    cin >> total; 
// Check if the value entered is outside the range (1…100). 
    if (total < 1 || total > 100) 
    { 
     cout << "This number is out of range!" << endl; 
     return 1; 
    } 
// Set counter to 0. 
    counter = 0; 
// While (counter is less than total) 
    // Get the value from the file and store it in grade. 
    // Accumulate its value in sum. 
    // Increment the counter. 
    while (counter < total) 
    { 
    inFile >> grade; 
    sum += grade; 
    counter++; 
    } 
// Print message followed by the value returned by the function average (sum,total). 
    cout << "The average is: " << average(sum,total) << endl << endl; 

    inFile.close(); 

    return 0; 

} 
int average(int a, int b) 
{ 

return static_cast <int> (a) /(static_cast <int> (b)); 
} 

我試圖將while循環轉換爲for循環,但是當我調試時我得到一個無限循環。建立我的解決方案時沒有錯誤。我不確定要添加哪些其他細節。

+0

在您發佈之前,這只是第二次看的問題。 – sjsam

回答

5

您正在增加for循環中的total的值。因此,如果您繼續輸入正值,counter永遠不會達到total

也許你打算在循環中使用sum而不是total

for (counter = 0; counter < total; counter++) 
{ 
    inFile >> grade;   
    cout << "The value read is " << grade << endl; 
    sum = sum + grade; 
} 
1

您正在使用錯誤的變量的名稱,的total值在for循環,使其成爲一個無限循環的增加,用於存儲金額和for-loop終止條件不同的變量名。