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

Выше это цикл while, который у меня был для моей первоначальной программы, а ниже - моя попытка преобразования этого в цикл for.Как преобразовать цикл while в цикл for в C++?

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)); 
} 

Я попытался преобразовать во время цикла, чтобы для цикла, но когда я отладки я получаю бесконечный цикл. При создании моего решения ошибок нет. Я не уверен, что добавить другие детали.

+0

Это был вопрос второго взгляда, прежде чем вы разместили его здесь. – sjsam

ответ

5

Вы увеличиваете значение total в цикле for. Следовательно, 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-loop условия завершения.

Смежные вопросы