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));
}
Я попытался преобразовать во время цикла, чтобы для цикла, но когда я отладки я получаю бесконечный цикл. При создании моего решения ошибок нет. Я не уверен, что добавить другие детали.
Это был вопрос второго взгляда, прежде чем вы разместили его здесь. – sjsam